python爬虫类

requests模块

python使用requests模块发起网络请求,也可使用python内置urllib模块,但很繁琐

安装:pip install requests

import requests

response = requests.get(url='请求地址',param={参数:'参数'},headers={请求头:传入字典}) #使用get请求
requests.post(url='请求地址',headers={请求头:传入字典},data='请求体数据') #post请求
#UA伪装
headers = {
  'User-Agent' 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0'
}
response = requests.get(url='请求地址',headers=headers) 

#获取数据
response.encoding = 'utf-8' #对相应数据进行编码
response.text #获取文本数据,一般是 html页面数据
response.josn() #获取json数据
response.content #返回二进制数据

#使用代理
response = requests.get(url='请求地址',headers=headers,proxies={'https':'ip'})  #键是代理类型

Session对象

在requests中还有个session对象,session对象是一个会话对象,它可以在多个请求之间保持一些参数和状态,即自动关联cookie

import requests
#对象创建
session = requests.Session()
#session内调用的方法同request一样,不过在每次请求的时候会携带着网站对该对话设置的信息,如cookie

正则表达式

导入re模块即可使用正则表达式

import re

#从头匹配
result = re.match("我是匹配规则","我是匹配对象") 
result.span() #位置如  (0,3) 匹配的占位
result.group() #获取匹配到的值
#搜索整个字符串,找到第一个就结束
result = re.search("我是匹配规则","我是匹配对象") 
result.span() #位置如  (0,3) 匹配的占位
result.group() #获取匹配到的值
#找全部,返回一个列表
result = re.findall("我是匹配规则","我是匹配对象",re.s) #re.s还可以是re.m,分为多行和单行匹配,re.s是多行,其匹配时会略过/n换行符 
print(result) # []

xpath模块

安装: pip install lxml

解析: 实例化一个etree对象

from lxml import etree
etree.parse(file) #解析本地文件
etree.HTML('text') #解析文本数据

#使用例子
tree = etree.parse('test.html')
r = tree.xpath('/html/body/div') #根据html内标签包裹形式,从顶到底解析,返回一个列表,列表内存着解析出来的对象
# /表示从根节点开始定位,一个 / 代表一个层级
# // 从该节点的子孙元素选取
r = tree.xpath('//div[@class="momo"]/p[1]')[0] #返回的是一个列表,在标签内加上[] 可更具体定位
r = tree.xpath('//*[@id="momo"]/p[1]/test()') #使用/test() 获取标签内直系的文本内容,以列表形式返回,*代表所有标签
t = r.xpath('./div/test()') #获取的对象标签还可以继续通过xpath定位,使用./开头代表从该标签处定位

xpath定位语法 www.runoob.com/xpath/xpath-syntax.html

www.cnblogs.com/mxjhaima/p/13775844.html

xpath的定位可以在浏览器元素内,右键对应标记复制,复制xpath格式即可

xpath用于解析html或其他标签类文本的信息

aiohttp 异步请求

安装:pip install aiohttp

import aiohttp
import asyncio

#异步方法
async method(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            result = await response.content() #获取数据是阻塞的,需要使用 await挂起
tasks = [] 
for url in urls:
    c = method(i)
    task = asyncio.ensure_future(c)  #创建协程任务
    tasks.append(task) #将任务加入列表
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks)) 

selenium模块

安装: pip install selenium
驱动: selenuim使用需要下载浏览器对应版本的驱动程序

selenium启动的是一个全新的(与手动打开的不一致)的浏览器

from selenuim import webdriver

web = webdriver.Chrome(executable_path='驱动地址')
#具体使用 https://blog.csdn.net/kobepaul123/article/details/128796839
# 		https://www.selenium.dev/zh-cn/documentation/

#在html标签中若遇到需要的元素在 iframe标签中,需要切换作用于
web.switch_to_frame('iframe的id')

#隐藏浏览器
#浏览器启动选项
option=webdriver.ChromeOptions()
#指定为无界面模式
option.add_argument('--headless')
# option.headless=True  或者将上面的语句换成这条亦可
#创建Chrome驱动程序的实例
driver=webdriver.Chrome(options=option)

scrapy框架

一些使用教程:
https://blog.csdn.net/ck784101777/article/details/104468780
https://www.runoob.com/w3cnote/scrapy-detail.html
官网:https://scrapy.org/

安装:pip install scrapy
scrapy使用时,需要使用scrapy的指令来创建项目以及运行项目
scrapy startproject 项目名 在当前目录下创建项目
scrapy genspider 爬虫名 域名 创建爬取对应域名的爬虫,需要再项目的spider目录下创建,域名可以去掉,域名是做限制的一半不用
scrapy crawl 爬虫名 运行对应爬虫 后面填上 --nolog 可不显示日志
目录大致结构:

|-ProjectName              #项目文件夹
   |-ProjectName           #项目目录
      |-items.py               #定义数据结构
      |-middlewares.py    #中间件
      |-pipelines.py          #数据处理
      |-settings.py            #全局配置
      |-spiders               
          |-__init__.py       #爬虫文件
          |-baidu.py
   |-scrapy.cfg               #项目基本配置文件

爬取前一般要修改setting.py内的配置的ua信息和取消遵守robot协议

posted @ 2025-08-12 22:20  LittleD-  阅读(18)  评论(0)    收藏  举报