在使用 Python 做爬虫的时候,我们需要伪装头部信息骗过网站的防爬策略,Python 中的第三方模块 fake_useragent 就很好的解决了这个问题,它将给我们返回一个随机封装了好的头部信息,我们直接使用即可

fake_useragent 的使用
安装 fake_useragent

pip install fake_useragent

示例:

from fake_useragent import UserAgent

# 实例化 UserAgent 类
ua = UserAgent()

# 对应浏览器的头部信息
print(ua.ie)
print(ua.opera)
print(ua.chrome)
print(ua.firefox)
print(ua.safari)

# 随机返回头部信息,推荐使用
print(ua.random)

运行结果:

(adnice) adnice:Downloads zhangyi$ python3 fake.py
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; SLCC1; .NET CLR 1.1.4322)
Opera/9.80 (Windows NT 6.1; U; fi) Presto/2.7.62 Version/11.00
Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1500.55 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:23.0) Gecko/20131011 Firefox/23.0
Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27
Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2117.157 Safari/537.36

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.errors.FakeUserAgentError: Maximum amount of retries reached

大概意思是:这个模块尝试请求一个东西已达到最大重试次数

打开这个模块的源码进行查看发现这个库会引用在线资源,所以这个模块是进行几次尝试请求一个网站的 Json 数据,但是因为各种原因请求超时,所以就会报这个错误

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

解决方案:
首先第一步要进行更新 fake_useragent

pip install --upgrade fake_useragent

1. 在实例化的时候指定一些参数
禁用服务器缓存

ua = UserAgent(use_cache_server=False)

不缓存数据

ua = UserAgent(cache=False)

忽略ssl验证

ua = UserAgent(verify_ssl=False)

一般的话,通过上述解决方案都能解决了,但是我就比较悲催了,还是没解决…

2. 使用临时 Json 文件
在 fake_useragent\settings.py 发现了几个 URL,其中有一些是打不开的,所以,我们将能打开的 URL 的 Json 文件保存在本地

wget https://fake-useragent.herokuapp.com/browsers/0.1.11

这时我们就会得到一个 0.1.11 的文件,将文件名改为 fake_useragent_0.1.11.json

mv 0.1.11 fake_useragent_0.1.11.json

然后找到我们的临时文件目录(每个系统都不一样,例如 Ubuntu 在 /tmp 下)

(edison) adnice:T zhangyi$ python3
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tempfile
>>> tempfile.gettempdir()
'/var/folders/6_/p67xz49j5wd5lzx7s2cz1cdr0000gn/T'
>>>

最后将文件拷贝到临时目录中即可

cp fake_useragent_0.1.11.json /var/folders/6_/p67xz49j5wd5lzx7s2cz1cdr0000gn/T/

当我们再次实例化 UserAgent 的时候,就会先读取本地的临时文件,这样实例化的时候就不会报错了

参考文章:https://blog.csdn.net/huiyanshizhu/article/details/84952093
————————————————
版权声明:本文为CSDN博主「极客点儿」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yilovexing/article/details/89044980

Python3 fake_useragent 模块的使用和报错解决方案的更多相关文章

  1. Python使用requests模块访问HTTPS网站报错`certificate verify failed`

    使用requests模块访问HTTPS网站报错: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Nam ...

  2. Python3.x:import urllib2报错解决方案

    Python:import urllib2报错解决方案 python2和3有些不一样: python2:输出为print 'hello world' python3:输出为print('hello w ...

  3. RabbitMQ>Erlang machine stopped instantly (distribution name conflict?). The service is not restarted as OnFail is set to ignore.-报错解决方案 原来是NNND。。。

    >Erlang machine stopped instantly (distribution name conflict?). The service is not restarted as ...

  4. Updates were rejected because the remote contains work that you do(git报错解决方案)

    Updates were rejected because the remote contains work that you do(git报错解决方案) 今天向GitHub远程仓库提交本地项目文件时 ...

  5. JMeter 报告监听器导入.jtl结果文件报错解决方案

    JMeter 报告监听器导入.jtl结果文件报错解决方案   by:授客 QQ:1033553122   1. 问题描述 把jmeter压测时生成的 .jtl结果文件导入监听器报告中,弹出如下错误提示 ...

  6. php 500报错解决方案

    php 500报错解决方案 1 先看nginx error.log 指定的错误日记文件路径 找到这个日记文件看 里面信息 2 再看 php-fpm.conf 里面指定的PHP错误日记的路径 具体如下& ...

  7. mysql主从复制报错解决方案

    mysql主从复制报错解决方案 我先制造个错误 在slave删除个info3字段 然后在master 在info3插入数据 报错如下<pre> Last_SQL_Errno: 1054 L ...

  8. 转:CentOS上安装LAMP之第三步:MySQL环境及安装过程报错解决方案(纯净系统环境)

    这是AMP运行环境中最后配置的环境: 惯例传送门: 1.编译安装MySQL cd /home/zhangatle/tar tar zxvf mysql-.tar.gz cd mysql- cmake ...

  9. Eclipse开发Android项目报错解决方案详细教程,最新版一篇就够了!

    本文记录刚接触Android开发搭建环境后新建工程各种可能的报错,并亲身经历漫长的解决过程(╥╯^╰╥),寻找各种偏方,避免大家采坑,希望能帮助到大家. 报错信息 出错一:The import and ...

随机推荐

  1. 因改漏洞而引申了解的Cookie机制!

    近期因为修改漏洞:Appscan扫描漏洞:加密会话(SSL)Cookie中缺少Secure属性,而涉及到Cookie有关的知识,现结合该漏洞的修复过程和了解的cookie知识总结一下. 一.加密会话( ...

  2. 用java语言将数据库中的数据表转换为xml文件的通用程序(细化)

    转自:https://www.cnblogs.com/wudage/p/7650685.html 总是在网络上copy别人的源代码,今天我也贴出自己今天写的源码,相信这个程序会对大家在平时的工作中需要 ...

  3. PHP 基于redis的分布式锁

    <?php class ProcessRedisLock { /** * redis key 前缀 */ const KEY_PREFIX = 'PROCESS_REDIS_LOCK:'; /* ...

  4. CAS 的问题

    cas这么好用,那么有没有什么问题呢?还真有 ABA问题 CAS需要在操作值的时候检查下值有没有发生变化,如果没有发生变化则更新,但是如果一个值原来是A,变成了B,又变成了A,那么使用CAS进行检查时 ...

  5. Jupyter Notebook修改默认的工作目录

    Jupyter Notebook修改默认的工作目录 方法1:通过配置文件修改 只适合从命令行启动notebook生成配置文件,如果你已经在windows环境变量中设置好了jupyter noteboo ...

  6. Mybatis返回表自增id

    在Mapper中,设置insert中添加useGeneratedKeys = "true"   keyProperty = "id" keyColumn=&qu ...

  7. MyBatis日记(四):MyBatis——insert、update、delete、select

    MyBatis简单增删改查操作,此处所做操作,皆是在之前创建的MyBatis的Hello world的工程基础上所做操作. 首先在接口文件(personMapper.java)中,添加操作方法: pa ...

  8. VLAN实验5:利用三层交换机实现VLAN间路由

    实验环境: 实验拓扑图:   实验编址: 实验步骤:1.基本配置按照实验编址表在PC上进行基本的IP地址配置,三层交换机上先不做任何配置. 测试PC1与PC2的连通性 正常 测试PC1与PC3的连通性 ...

  9. 【Miscalculation UVALive - 6833 】【模拟】

    题目分析 题目讲的是给你一个串,里面是加法.乘法混合运算(个人赛中误看成是加减乘除混合运算),有两种算法,一种是乘法优先运算,另一种是依次从左向右运算(不管它是否乘在前还是加在前). 个人赛中试着模拟 ...

  10. java代码获取项目版本号实例

    package com.hzcominfo.application.etl.settings.web.controller.highconfig; import com.hzcominfo.appli ...