在使用 Python 做爬蟲的時候,我們需要偽裝頭部信息騙過網站的防爬策略,Python 中的第三方模塊 fake_useragent
就很好的解決了這個問題,它將給我們返回一個隨機封裝了好的頭部信息,我們直接使用即可
fake_useragent的安裝
pip install fake_useragent
fake_useragent的使用
from fake_useragent import UserAgent # 隨機生成ua,推薦使用 UA = UserAgent().random request.headers['User-Agent']=UA
fake_useragent使用過程的發生的錯誤
socket.timeout: timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "d:\programdata\anaconda3\lib\site-packages\fake_useragent\utils.py", lin e 166, in load verify_ssl=verify_ssl, File "d:\programdata\anaconda3\lib\site-packages\fake_useragent\utils.py", lin e 122, in get_browser_versions verify_ssl=verify_ssl, File "d:\programdata\anaconda3\lib\site-packages\fake_useragent\utils.py", lin e 84, in get raise FakeUserAgentError('Maximum amount of retries reached') fake_useragent.errors.FakeUserAgentError: Maximum amount of retries reached
依據報錯信息提示,推斷是網絡超時造成,從網查閱資料得知,這個庫會引用在線資源,其源碼 fake_useragent\settings.py 相關配置如下所示:

# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os import tempfile __version__ = '0.1.11' DB = os.path.join( tempfile.gettempdir(), 'fake_useragent_{version}.json'.format( version=__version__, ), ) CACHE_SERVER = 'https://fake-useragent.herokuapp.com/browsers/{version}'.format( version=__version__, ) BROWSERS_STATS_PAGE = 'https://www.w3schools.com/browsers/default.asp' BROWSER_BASE_PAGE = 'http://useragentstring.com/pages/useragentstring.php?name={browser}' # noqa BROWSERS_COUNT_LIMIT = 50 REPLACEMENTS = { ' ': '', '_': '', } SHORTCUTS = { 'internet explorer': 'internetexplorer', 'ie': 'internetexplorer', 'msie': 'internetexplorer', 'edge': 'internetexplorer', 'google': 'chrome', 'googlechrome': 'chrome', 'ff': 'firefox', } OVERRIDES = { 'Edge/IE': 'Internet Explorer', 'IE/Edge': 'Internet Explorer', } HTTP_TIMEOUT = 5 HTTP_RETRIES = 2 HTTP_DELAY = 0.1
經過試驗發現是由於其中 BROWSERS_STATS_PAGE = 'https://www.w3schools.com/browsers/default.asp' 的網址打不開導致的超時報錯。
解決辦法:將該文件下載到本地,放置到相應的文件夾下。
瀏覽器訪問 https://www.w3schools.com/browsers/default.asp 網址,然后 Ctrl+S 將文件另存為 fake_useragent_0.1.11.json,注意這個名字不能變,要和源文件配置的名字一樣,不然會導致無法訪問。至於把保存的文件放置到那個位置,可以通過查看配置源碼:
DB = os.path.join( tempfile.gettempdir(), 'fake_useragent_{version}.json'.format( version=__version__, ), )
發現,它是和 tempfile.gettempdir() 的路徑拼接成DB完整路徑的,因此tempfile.gettempdir() 的路徑就是存放 fake_useragent_0.1.11.json 文件的路徑。 如下圖所示,只需要把保存的json文件放到該目錄下,就可以正常訪問了,在也不會出現超時的問題!
注意:如果 CACHE_SERVER 不是 https://fake-useragent.herokuapp.com/browsers/0.1.11 請更新一下庫 :
pip install --upgrade fake_useragent
本文參考博文:https://blog.csdn.net/yilovexing/article/details/89044980