爬虫
requests模块
安装命令如下:
pip install requests
或者
pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple
requests 模块的基本使用
1.发请求
1.1 requests 发送 GET 请求
response = requests.get(url, headers={}, params={},proxies={})
1.2 requests 发送 post 请求
response = requests.post(url, data={}, headers={}, params={},proxies={})
1.3 注意点
post一般带数据访问登录页面,但get一般是带登录后的cookie访问登录页面
2. response 响应对象
response.content
bytes, 未解码
response.text
str, 解码了,但是解码的编码集是推测出来的,故结果不一定正确
response.content.decode('编码集,默认utf8')
response.json() 将响应的json字符串内容转化为字典
3.设置cookie
可以记录状态,访问登录后的页面,还可以有一定的反爬作用
3.1.headers中添加Cookies参数
headers = {
'User-Agent':'******',
'Cookie':' ******'
}
3.2.请求参数中的cookies参数
cookies ={'key' : 'value'}
requests.get/post(++++++ ,cookies=cookies)
3.3.session自带cookie
session = requests.session()
session.post() 先登录,获取cookie
session.get() 再自带cookie访问登录后的页面
4.数据提取
4.1 正则表达式
单个字符匹配: . [] \d \D \s \S \w \W
多个字符匹配:* + ? {m} {m,n}
开始与结尾: ^ $
其他: [^指定字符]
分组:定义:()
起别名:(?P<name> ***)
引用分组:\num (?P=name)
贪婪匹配与非贪婪匹配:
.* 尽可能多的匹配
.*? 尽可能少的匹配
4.2 re模块
re.match(pattern, string, flags) 从头就匹配,对象, 获取结果用group groups
re.search(pattern, string, flags) 返回第一次匹配的结果, 对象,获取结果用group groups
re.findall(pattern, string, flags) 无分组,返回所有匹配的字符串
有分组,返回所有匹配字符串的分组部分 列表
re.split(pattern, string, maxsplit=0, flags=0) 从匹配的地方分割, 列表
re,sub(pattern, repl, string, count=0, flags=0) 替换匹配的部分
re.compile(pattern,flags=0) 生成一个pattern对象
4.3 jsonpath
记住模式: $ @ .or[] .. * [] [,] ?() ()
安装:pip install jsonpath [-i https://pypi.tuna.tsinghua.edu.cn/simple]
使用: import jsonpath
ret = jsonpath.jsonpath(json_dict, 'pattern')
json.dumps(dict/list) 将字典或者列表转化为字符串
json.dump(dict/list, f) 将字典或者列表转化为字符串,并且写入到文件中
4.4 xpath
记住模式:nodename / // . .. @ text()
4.5 lxml
背后使用的是xpath,
使用:from lxml import etree
element = etree.HTML(str)
str = etree.tostring(element).decode()
result = element.xpath('****')