import requests
url = 'https://wh.58.com/sou/?key=python%E5%B7%A5%E7%A8%8B%E5%B8%88'
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'
, 'referer': 'https://wh.58.com/sou/?key=python'
}
res = requests.get(url, headers=headers)
with open('6.html', 'w') as f:
f.write(res.content.decode('utf-8'))
f.close()
requests是一个简单的http库,基于urlib编写,相比urlib更加简单易用
使用requests.get请求获取网页,headers请求头进行伪装
鼠标点击右键--检查--NetWork点击一个请求可以查看这个请求的请求头等各项参数
请求得到的是一个响应对象
<Response [200]>
使用text或content可以的到网页源码
text中存的是Beautifulsoup根据猜测的编码方式将content内容编码成字符串
content返回的是byte类型
大多数情况使用text,若text出现乱码使用content.decode()自定义编码
代码运行生成的html文件
使用浏览器查看文件