一、requests模块
response = requests.get(‘url’)
response.content
response.text
response.encoding
response.apparent_encoding
response.status_code
response.cookies.get_dict() # 获取cookie
response.headers() 响应头
requests.request(
method='提交方式,',
url='提交的地址',
params='get方式在URL中传递的参数', # 字典格式
data='在请求体里传递的数据', # 字典或字符串格式
json='在请求体里传递的数据,(字典中嵌套字典必须用json)', # 序列化一下
headers='定制请求头的信息', # Referer:前一个访问的网址 User-Agent:什么浏览器。 都可以伪造
cookies='放在请求头中发过去',
files='上传文件',
auth='基本认证(headers中加入加密的用户名和密码)',
timeout='请求和响应的超时时间',
allow_redirects='是否允许重定向',
proxies='代理',
verify='是否忽略证书',
cert='证书文件',
stream='一点一点拿结果'
)
requests.Session() # 自动保存历史访问获取的请求头和请求体信息,下次访问自动携带信息
二、BeautifulSoup模块
该模块用于接收一个HTML或XML字符串,然后将其进行格式化,将其变成一个对象嵌套对象的对象。
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, features=‘html.parser’)
features引擎,用什么引擎解析,parser是python内置引擎,速度一般。lxml是c语言写的,速度快。
v1 = soup.find(‘div’) # 返回找到的第一个
soup.find(id=‘i1’)
soup.find(‘div’, id=‘i1’)
soup.select(’#link’) #select通过选择器的方式查找
v2 = soup.find_all() # 返回一个列表
obj = v1
obj = v2[0]
obj.text # 标签对象的文本
obj.attrs # 标签对象的属性
模块方法详解:
soup = BeautifulSoup('html', features='parser')
tag = soup.find(name='a')
tag.attrs # 获取标签属性
tag.attrs = {'id': 'v'} # 添加、修改标签的属性
del tag.attrs['href'] # 删除标签的属性
tag.string = '' # 修改标签文本
tag.name # 获取标签名
tag.get_text() # 获取标签内部文本
tags1 = soup.find('body').children # 只找孩子
# children 包含两种类型 一种文本(换行),一种标签
tags2 = soup.find('body').descendants # 子子孙孙,递归着找
soup.find('body').clear() # 保留标签名
soup.find('body').decompose() # 不保留标签名
v = soup.find('body').extract() # 返回标签名
tag = soup.find('body')
tag.decode() # 把对象转化为字符串类型,包含当前标签
tag.encode() # 把对象转化为字节类型
tag.decode_contents() # 把对象转化为字符串类型,不包含当前标签
tag.encode_contents()
tag = soup.find(name='a', attrs={'class': 'sister'}, recursive=True, text='lacie')
# 满足括号内所有的条件,recursive是否递归,不递归只查儿子
tags = soup.find_all(name=['a', 'div']) # 或的意思
import re
rep = re.compile('^p')
v = soup.find_all(name=rep) # 匹配正则表达式
tag = soup.find('a')
v = tag.has_attr('id') # 标签内是否有这个属性
v = tag.get_text() # 获取标签的内部文本
tag = soup.find('body')
v = tag.index(tag.find('div'))
for i, v in enumerate(tag):
print(i, v)
三、例子
1、爬取汽车之家网站
import requests
from bs4 import BeautifulSoup
response = requests.get(url='http://www.autohome.com.cn/news/')
response.encoding = response.apparent_encoding
soup = BeautifulSoup(response.text, features='html.parser')
target = soup.find(id='auto-channel-lazyload-article')
li_list = target.find_all('li')
for i in li_list:
a = i.find('a')
if a:
print(a.attrs.get('href'))
txt = a.find('h3').text
print(txt)
img_url = a.find('img').attrs.get('src')
print(img_url)
img_response = requests.get(url='http:'+img_url)
# file_name = str(uuid.uuid4()) + '.jpj'
# with open(file_name, 'wb') as f:
# f.write(img_response.content)
2、自动登录抽屉
import requests
post_dict = {
'phone': 'aaa',
'password': 'aaa',
'oneMonth': 1
}
s = requests.Session()
response = s.post(url="https://dig.chouti.com/login",
data=post_dict,
headers={
'referer': 'https://dig.chouti.com/',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}
)
print(response.text)
cookie_dict = response.cookies.get_dict()
print(cookie_dict)