1. 程式人生 > 其它 >fake_useragent 模組的使用和網路超時報錯的解決方案

fake_useragent 模組的使用和網路超時報錯的解決方案

在使用 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
View Code

經過試驗發現是由於其中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

天青色等煙雨而我在等你!