在進行Scrapy開發的時候,需要使用UA中間件,這里就采用了fake-useragent來隨機獲取瀏覽器的UA值,但貌似直接訪問的話有異常:
File "/Users/mazhiyong/.virtualenvs/scrapy/lib/python3.7/site-packages/fake_useragent/utils.py", line 154, in load for item in get_browsers(verify_ssl=verify_ssl): File "/Users/mazhiyong/.virtualenvs/scrapy/lib/python3.7/site-packages/fake_useragent/utils.py", line 97, in get_browsers html = get(settings.BROWSERS_STATS_PAGE, verify_ssl=verify_ssl) File "/Users/mazhiyong/.virtualenvs/scrapy/lib/python3.7/site-packages/fake_useragent/utils.py", line 84, in get raise FakeUserAgentError('Maximum amount of retries reached') fake_useragent.errors.FakeUserAgentError: Maximum amount of retries reached
貌似是網絡訪問問題。
綜合資料,解決辦法如下:
當然前提是先安裝:
pip install fake-useragent
如果已經安裝過,記得更新下:
pip install -U fake-useragent
然后手動下載UA的緩存文件,訪問地址為;
https://fake-useragent.herokuapp.com/browsers/0.1.11
目前最新版本是這個,以后可以根據版本不同再調整。
1、將下載的文件命名為: fake_useragent_0.1.11.json 並放入linux 或者 windows的臨時目錄。然后就可以正常使用fake-useragent了。
獲取臨時目錄 方法:
>>> import tempfile >>> tempfile.gettempdir() '/tmp'
2、將fake_useragent_0.1.11.json存儲到指定位置,然后使用fake-useragent的時候指定文件路徑:
def get_header(): location = os.getcwd() + '/fake_useragent.json' ua = fake_useragent.UserAgent(path=location) return ua.random
3、也可以自己直接解析fake_useragent_0.1.11.json文件使用。
使用示例:
>>> from fake_useragent import UserAgent >>> ua = UserAgent(path="/Volumes/DATA/fake_useragent_0.1.11.json") >>> ua.random 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.14 (KHTML, like Gecko) Chrome/24.0.1292.0 Safari/537.14'
參考文章:
https://pypi.org/project/fake-useragent/
https://blog.csdn.net/shaooping/article/details/90296667
https://www.cnblogs.com/rwxwsblog/p/10174940.html