在使用 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. java static变量及函数

    java以类为基础,没有游离在类之外单独存在的变量.所以,c++中的全局变量,在java中应该是不存在的.java中有的是成员变量和成员方法.当成员前以static修饰时,即为静态成员变量或静态成员方 ...

  2. 【WPF】EntityframeworkCore Update注意事项

    The instance of entity type 'Book' cannot be tracked because another instance with the same key valu ...

  3. iManager微服务自定义上传数据的两种方法

    背景 当数据量大时,通过浏览器上传可能速度较慢,可以使用以下两种方式进行数据导入. 方法一 1.访问k8s主页(31234端口) 找到所创建的微服务的命名空间(例如icloud-native-xxx) ...

  4. mybatis批量更新报错 org.mybatis.spring.MyBatisSystemException

    具体报错信息: org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.Bin ...

  5. FreeBSD安装后使用su命令显示sorry的解决办法

    FreeBSD中,可以使用su命令成为root用户,但FreeBSD对执行su命令的用户进行了更严格的限制,能使用su命令的用户必须属于wheel组(root的基本属组,组ID为0),否则就不能通过 ...

  6. 关于header file、static、inline、variable hides的一点感想

    前言 先看一段代码 #ifndef _INLINE_H #define _INLINE_H template<typename T> static inline T my_max(T a, ...

  7. 进程间通信之数据传输--FIFO

    One of the fundamental features that makes Linux and other Unices useful is the “pipe”. Pipes allow ...

  8. i++和++i的真正区别

    原文:https://blog.csdn.net/c15158032319/article/details/78209740 记得刚开始学编程的时候还是从c语言开始的,还是看的谭浩强写的那本书,上面对 ...

  9. QA流程

    一.测试人员的介入时间 1.当产品经理与业务人员制定需求的时候,测试人员不宜介入: 2.当下一期的需求原型出来以后,这个时候就进入了需求评审.需求分析阶段,此时,测试人员应该介入: 3.当开发人员在编 ...

  10. 小米BL不解锁刷机

    关于小米NOTE顶配近期解锁的问题中发现还有很多人不会用9008模式刷机,现出个简单教程方便米粉们救砖.硬件:小米NOTE顶配手机 win10系统的电脑 手机与电脑相连的数据线软件:老版本的mifla ...