Python requests 库爬取网页

2024-06-10阅读数:192
上一篇: Python爬虫常见问题
下一篇:Python requests添加User Agent
# coding=utf-8
import requests
html = requests.get('http://www.spiderbuf.cn/list').text
print(html)

# 在Windows环境下,Python爬取网页出现乱码通过是因为Windows环境默认编码是GBK而大部分网页编码是UTF-8
# 此时可以利用requests库的content方法,它会自动根据网页编码进行转换
# requests避免乱码的爬虫代码修改如下:

import requests
html_bytes = requests.get('http://www.spiderbuf.cn/list').content
# requests content返回的是bytes类型,需要转换成字符串方便使用
html = html_bytes.decode()
print(html)