直接用fake_useragent随机生成useragent时,经常出现timeout错误,可以把json文件手动下载回来,用path参数指定这个json的路径
ua = UserAgent(path='fake_useragent.json')
上述方法在旧版(版本号0.1.11)中可用,但是在新版的fake_useragent(版本号1.0.1)中报错:
FakeUserAgent.__init__() got an unexpected keyword argument 'path'
解决方法是把path改成cache_path,即
ua = UserAgent(cache_path='fake_useragent.json')
不知道从哪个版本开始,参数名path改成了cache_path。如果不确定用哪个参数名,看一下UserAgent源码的参数列表就知道了
代码:
from fake_useragent import UserAgent
# 本地获取
ua = UserAgent(cache_path=r"D:\PyCharmWorkSpace\bar\fake_useragent.json")
# ua.random随机获取一个请求头
print(ua.random)
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MS-RTC LM 8; .NET4.0C; .NET4.0E; InfoPath.3)
借鉴:python本地调用新版UserAgent - 『编程语言讨论求助区』 - 吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn