部分网站做了反爬虫机制,不允许程序访问网站的数据,而使用同一个useragent(用户代理)短时间爬取大量数据也可能被网站反爬虫程序识别。为了更好地模拟浏览器地工作,可以使用第三方库fake-useragent生成假的useragent字符串伪装浏览器,从而绕过一些网站的反爬虫措施。
首先在命令行中输入pip install fake-useragent
安装fake-useragent
可以继续在命令行中输入pip show fake-useragent
查看fake-useragent库的相关信息,结果如下(可以包的主页Home-Page查看详细信息):
Name: fake-useragent
Version: 1.5.1
Summary: Up-to-date simple useragent faker with real world database
Home-page: https://github.com/fake-useragent/fake-useragent
Author:
Author-email: Melroy van den Berg <[email protected]>, Victor Kovtun <[email protected]>
License:
Location: C:\Users\89660\AppData\Local\Programs\Python\Python312\Lib\site-packages
Requires:
Required-by:
运行代码:
from fake_useragent import UserAgent
# 创建UserAgent实例
ua = UserAgent()
# 打印随机的UserAgent字符串,可选择不同的浏览器
print(ua.chrome)
print(ua.chrome)
print(ua.edge)
print(ua.firefox)
print(ua.safari)
print(ua.safari)
运行结果:
Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Mobile Safari/537.36
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36
Mozilla/5.0 (iPhone; CPU iPhone OS 17_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) EdgiOS/121.0.2277.107 Version/17.0 Mobile/15E148 Safari/604.1
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0 Config/92.2.7601.2
Mozilla/5.0 (iPhone; CPU iPhone OS 17_0_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1
Mozilla/5.0 (iPhone; CPU iPhone OS 17_0_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1
使用httpbin工具检测:
from urllib.request import Request, urlopen
from fake_useragent import UserAgent
# 测试工具url地址
url = 'http://httpbin.org/get'
# 创建UserAgent实例
ua = UserAgent()
# 伪装请求头
headers = {'user-agent': ua.chrome}
# 封装Request对象
req = Request(url, headers=headers)
# 发送请求
resp = urlopen(req)
# 读取响应内容
print(resp.read().decode())
运行结果(生成的user-agent字符串是随机的)
{
"args": {},
"headers": {
"Accept-Encoding": "identity",
"Host": "httpbin.org",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
"X-Amzn-Trace-Id": "Root=1-66e6a19f-67824bec2bdcca50710aed6a"
},
"origin": "111.8.72.145",
"url": "http://httpbin.org/get"
}