在使用 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. Newtonsoft.Json.Linq.JObject 遍历验证每个属性内容

    业务需求,拦截器验证每个请求inputstream(实际是application/json流)的数据,但是json反序列化实体格式不同. var req = filterContext.Request ...

  2. DB2数据库中DB2字符串类型

    DB2字符串是DB2数据库中的基础知识,下面就为您分类介绍DB2字符串,供您参考,如果您对DB2字符串方面刚兴趣的话,不妨一看. DB2字符串是字节序列.DB2字符串包括 CHAR(n) 类型的定长字 ...

  3. 一道经典面试题,atoi函数的实现

    参考资料 (1)atoi函数的实现 (2)<剑指offer> 题目分析 本题需要注意的有几个方面: (1)检查输入参数,指针是否为NULL: (2)去除字符串前面的空格 (3)处理正负符号 ...

  4. 使用kubeadm 新加入节点(原始token过期后)---转发

    kubeadm join kubeadm init 安装完成后你会得到以下的输出,使用join指令可以新增节点到集群,此token 有效期为24小时 You should now deploy a p ...

  5. 51nod 1254 最大子段和 V2

    N个整数组成的序列a[1],a[2],a[3],…,a[n],你可以对数组中的一对元素进行交换,并且交换后求a[1]至a[n]的最大子段和,所能得到的结果是所有交换中最大的.当所给的整数均为负数时和为 ...

  6. python开发总结

    1.思维缜密的编程逻辑 2.满足明确的目的需求 3.运用现成的轮子加以改造 4.学会装饰自己的程序 5.化繁为简 6.多用配置文件作为入口 7.注意扩展兼容

  7. 【python】raise_for_status()抛出requests.HTTPError错误

    1.首先看下面代码的运行情况 import requests res = requests.get("https://www.csdn.net/eee", headers=head ...

  8. RMQ问题及ST表

    RMQ(Range Minimum/Maximum Query)问题指的是一类对于给定序列,要求支持查询某区间内的最大.最小值的问题.很显然,如果暴力预处理的话复杂度为 \(O(n^2)\),而此类问 ...

  9. linux 读取文件

    linux读取文件是经常要用到的操作,以下示例(说明看注释): #读取文件snlist.txt中的每一行内容赋给sn变量 while read sn do echo ">>> ...

  10. SpringBoot-设置定时任务

    @Scheduled为设置定时任务的注解. 参数常用的为两种: 第一种是fixedRate,表示以一种固定频率去执行,单位为毫秒:例如@Scheduled(fixedRate = 5000)  表示为 ...