scrapy 伪装代理和 fake_userAgent 的使用

 

From:https://www.cnblogs.com/hellangels333/p/8918938.html

fake-useragent 下载 和 使用方法:https://pypi.org/project/fake-useragent

 

伪装浏览器代理 在爬取网页是有些服务器对请求过滤的不是很高可以不用ip来伪装请求直接将自己的浏览器信息给伪装也是可以的。

第一种方法:

1.在setting.py文件中加入以下内容,这是一些浏览器的头信息

USER_AGENT_LIST = ['zspider/0.9-dev http://feedback.redkolibri.com/','Xaldon_WebSpider/2.0.b1','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) Speedy Spider (http://www.entireweb.com/about/search_tech/speedy_spider/)','Mozilla/5.0 (compatible; Speedy Spider; http://www.entireweb.com/about/search_tech/speedy_spider/)','Speedy Spider (Entireweb; Beta/1.3; http://www.entireweb.com/about/search_tech/speedyspider/)','Speedy Spider (Entireweb; Beta/1.2; http://www.entireweb.com/about/search_tech/speedyspider/)','Speedy Spider (Entireweb; Beta/1.1; http://www.entireweb.com/about/search_tech/speedyspider/)','Speedy Spider (Entireweb; Beta/1.0; http://www.entireweb.com/about/search_tech/speedyspider/)','Speedy Spider (Beta/1.0; www.entireweb.com)','Speedy Spider (http://www.entireweb.com/about/search_tech/speedy_spider/)','Speedy Spider (http://www.entireweb.com/about/search_tech/speedyspider/)','Speedy Spider (http://www.entireweb.com)','Sosospider+(+http://help.soso.com/webspider.htm)','sogou spider','Nusearch Spider (www.nusearch.com)','nuSearch Spider (compatible; MSIE 4.01; Windows NT)','lmspider (lmspider@scansoft.com)','lmspider lmspider@scansoft.com','ldspider (http://code.google.com/p/ldspider/wiki/Robots)','iaskspider/2.0(+http://iask.com/help/help_index.html)','iaskspider','hl_ftien_spider_v1.1','hl_ftien_spider','FyberSpider (+http://www.fybersearch.com/fyberspider.php)','FyberSpider','everyfeed-spider/2.0 (http://www.everyfeed.com)','envolk[ITS]spider/1.6 (+http://www.envolk.com/envolkspider.html)','envolk[ITS]spider/1.6 ( http://www.envolk.com/envolkspider.html)','Baiduspider+(+http://www.baidu.com/search/spider_jp.html)','Baiduspider+(+http://www.baidu.com/search/spider.htm)','BaiDuSpider','Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0) AddSugarSpiderBot www.idealobserver.com',]

2.在spider同级目录下建立一个MidWare文件价里面写一个HeaderMidWare.py文件 内容为

# encoding: utf-8
from scrapy.utils.project import get_project_settings
import randomsettings = get_project_settings()class ProcessHeaderMidware():"""process request add request info"""def process_request(self, request, spider):"""随机从列表中获得header, 并传给user_agent进行使用"""ua = random.choice(settings.get('USER_AGENT_LIST'))  spider.logger.info(msg='now entring download midware')if ua:request.headers['User-Agent'] = ua# Add desired logging message here.spider.logger.info(u'User-Agent is : {} {}'.format(request.headers.get('User-Agent'), request))pass

3.在setting.py文件中添加

DOWNLOADER_MIDDLEWARES = {
'projectName.MidWare.HeaderMidWare.ProcessHeaderMidware': 543,
}

 

 

第二种方法:fake_userAgent的使用

fake_userAgent是github上的开源项目
1.安装 fake_userAgent
    pip install fake-useragent

fake_userAgent 使用方法

from fake_useragent import UserAgent
import requestsua = UserAgent()
print(ua.ie)       #ie浏览器的user agent
print(ua.opera)    #opera浏览器
print(ua.chrome)   #chrome浏览器
print(ua.firefox)  #firefox浏览器
print(ua.safari)   #safri浏览器#最常用的方式
#写爬虫最实用的是可以随意变换headers,一定要有随机性。支持随机生成请求头
print(ua.random)
print(ua.random)
print(ua.random)######################################################请求的网址
url="http://www.baidu.com"#请求头
headers={"User-Agent":ua.random}#请求网址
response=requests.get(url=url,headers=headers)#响应体内容
print(response.text)#响应状态信息
print(response.status_code)#响应头信息
print(response.headers)


2.在spider同级目录下建立一个MidWare文件价里面写一个user_agent_middlewares.py文件内容为

# -*- coding: utf-8 -*-
from fake_useragent import UserAgentclass RandomUserAgentMiddlware(object):#随机跟换user-agentdef __init__(self,crawler):super(RandomUserAgentMiddlware,self).__init__()self.ua = UserAgent()self.ua_type = crawler.settings.get('RANDOM_UA_TYPE','random')#从setting文件中读取RANDOM_UA_TYPE值@classmethoddef from_crawler(cls,crawler):return cls(crawler)def process_request(self,request,spider):  ###系统电泳函数def get_ua():return getattr(self.ua,self.ua_type)# user_agent_random=get_ua()request.headers.setdefault('User_Agent',get_ua())pass

3.在setting.py中添加

RANDOM_UA_TYPE = 'random'##random    chromeDOWNLOADER_MIDDLEWARES = {'projectName.MidWare.user_agent_middlewares.RandomUserAgentMiddlware': 543, 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware':None,}

fake_userAgent伪装代理就配置好了,与第一种方法相比不用写一大串的浏览器头,那些浏览器头会在https://fake-useragent.herokuapp.com/browsers/0.1.7 中得到。


在第一次启用fake_userAgent的时候会有一些错,我认为是项目请求网络时需要缓存一些内容而导致的。

github地址:https://github.com/sea1234/fake-useragent

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/496108.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

readyState的五种状态详解【转】

在《Pragmatic Ajax A Web 2.0 Primer 》中偶然看到对readyStae状态的介绍,感觉这个介绍很实在,摘译如下: 0: (Uninitialized) the send( ) method has not yet been invoked. 1: (Loading) the send( ) method has been invoked, request i…

【读书笔记】《框架设计(第2版)CLR Via C#》中两个比较有趣的知识点

本季度公司要求阅读《框架设计(第2版)CLR Via C#》这本书,由于前两个月一直很忙,也没有时间阅读,偶尔阅读也是很晚回家以后临睡前拿起这经典之作读那么一个小节。最近利用周末可以说一鼓作气的看了大半本,感…

Python 使用 Scrapy 发送 post 请求的坑

From:https://www.jb51.net/article/146769.htm 使用 requests 发送 post 请求 先来看看使用requests来发送post请求是多少好用,发送请求 Requests 简便的 API 意味着所有 HTTP 请求类型都是显而易见的。 例如,你可以这样发送一个 HTTP POST …

Effective Java~46. 优先选择Stream 中无副作用的函数

纯函数&#xff08;pure function&#xff09;的结果仅取决于其输入&#xff1a;它不依赖于任何可变状态&#xff0c;也不更新任何状态。 坏味道 // Uses the streams API but not the paradigm--Dont do this! Map<String, Long> freq new HashMap<>(); try (S…

android applybatch,android – 使用applyBatch插入成千上万的联系人条目很慢

我正在开发一个应用程序&#xff0c;我需要插入大量的联系人条目。在当前时间约600个联系人&#xff0c;共有6000个电话号码。最大的联系人有1800个电话号码。截至今天的状态是&#xff0c;我创建了一个自定义帐户来保存联系人&#xff0c;因此用户可以选择在联系人视图中查看联…

[译]How to make searching faster

Here are some things to try to speed up the seaching speed of your Lucene application. Please see ImproveIndexingSpeed for how to speed up indexing. 以下是一些尝试提高lucene程序检索速度的方法. 如果需要提高索引速度,请看提高索引速度. Be sure you really need …

8个最高效的Python爬虫框架,你用过几个?

From&#xff1a;https://segmentfault.com/a/1190000015131017 1.Scrapy Scrapy是一个为了爬取网站数据&#xff0c;提取结构性数据而编写的应用框架。 可以应用在包括数据挖掘&#xff0c;信息处理或存储历史数据等一系列的程序中。。用这个框架可以轻松爬下来如亚马逊商品信…

android oreo 源码,android – Oreo:如何在源代码中找到所有受限制的系统调用?

哪些Syscalls在Android 8.0 Oreo中受限制&#xff1f;编辑&#xff1a;Syscall过滤背景过滤本身是Linux内核提供的标准功能,称为seccomp.所有AOSP都使用此功能来过滤上面链接的应用黑名单中列出的系统调用.脚本处理将黑名单列入特定于平台的自动生成过滤器,然后将其提供给secco…

Effective Java~57. 将局部变量的作用域最小化

优先选择 for 循环而不是 while 循环 例如&#xff0c;下面是遍历集合的首选方式 // Preferred idiom for iterating over a collection or array for (Element e : c) { ... // Do Something with e } 如果需要在循环中调用 remove 方法&#xff0c;首选传统的 for 循环代…

300+Jquery, CSS, MooTools 和 JS的导航菜单资源

如果你是网站前端开发人员&#xff0c;那么对你来说&#xff0c;也许做一个漂亮导航菜单会很得心应手。本文要为大家总结各种导航菜单的资源&#xff0c;以便让大家的网站前端开发的工作更方便更快速&#xff0c;只要选择现成的例子就可以应用于自己的网站了。本文收集的这些资…

轻量级分布式任务调度平台 XXL-JOB

From&#xff1a;https://www.cnblogs.com/xuxueli/p/5021979.html github 地址 及 中文文档地址&#xff1a;https://github.com/xuxueli/xxl-job 《分布式任务调度平台XXL-JOB》 一、简介 1.1 概述 XXL-JOB是一个轻量级分布式任务调度平台&#xff0c;其核心设计目标是开发…

畅玩4c刷android 9.0,华为畅玩4C电信版 CyanogenMod 13.0_Android_6.0.1 【HRT_chiwahfj】

本帖最后由 chiwah渔夫 于 2016-9-9 22:31 编辑【基本信息】ROM名称&#xff1a;华为畅玩4C电信版 CyanogenMod 13.0_Android_6.0.1ROM大小&#xff1a;617M适配版本&#xff1a;CyanogenMod 13.0_android_6.0.1测试机型&#xff1a;华为畅玩4C电信版作者简介&#xff1a;HRT团…

Effective Java~58. for-each 循环优先于传统的for 循环

传统的 for循环来遍历一个集合: // Not the best way to iterate over a collection! for (Iterator<Element> i c.iterator(); i.hasNext(); ) { Element e i.next();... // Do something with e } 迭代数组的传统 for 循环的实例 // Not the best way to iterate …

近期课余目标

http://acm.pku.edu.cn/JudgeOnline/ 按这个顺序做&#xff0c; 这些都是入门的水题 一.基本算法: (1)枚举. (poj1753,poj2965) (2)贪心(poj1328,poj2109,poj2586) (3)递归和分治法. (4)递推. (5)构造法.(poj3295) (6)模拟法.(poj1068,poj2632,poj1573,poj2993,poj2996) 二.图算…

html语言鼠标悬停特效,CSS3鼠标悬停文字幻影动画特效

这是一款CSS3鼠标悬停文字幻影动画特效。该特效利用before和after伪元素来制作当鼠标悬停在超链接文本上的时候的幻影效果。使用方法在页面中引入bootstrap.css、jquery和photoviewer.js文件。HTML结构在页面中添加一个元素&#xff0c;并设置它的data-hover属性和它的显示文字…

Python 爬虫 实例项目 大全

Github Python 爬虫&#xff1a;https://github.com/search?qpython爬虫 32个Python爬虫项目让你一次吃到撑&#xff1a;https://www.77169.com/html/170460.html 今天为大家整理了32个Python爬虫项目。 整理的原因是&#xff0c;爬虫入门简单快速&#xff0c;也非常适合新入…

Effective Java~23. 类层次优于标签类

标签类&#xff0c;包含一个标签属性&#xff08;tag field&#xff09;&#xff0c;表示实例的风格 // Tagged class - vastly inferior to a class hierarchy! class Figure {enum Shape { RECTANGLE, CIRCLE };// Tag field - the shape of this figurefinal Shape shape;/…

领导之所以是领导

最近系统很不安生&#xff0c;故障频出&#xff0c;12月30日下午15&#xff1a;00系统所有工单都无法在网元开通&#xff0c;用户缴费不能开机&#xff0c;只好手工执行&#xff0c;直到23&#xff1a;30才恢复。1月1日某个业务平台执行工单异常缓慢&#xff0c;导致系统1万多工…

可以叫板Google的一个搜索引擎 —— DuckDuckGo

From&#xff1a;https://blog.csdn.net/inter_peng/article/details/53223455 作为习惯了使用Google进行资料查询的我来说&#xff0c;如果没有Google&#xff0c;真的感觉很难受。纵使找了一些可以翻墙的软件&#xff0c;但无奈还是经常不稳定&#xff0c;总是时断时续的。Bi…

小米鸿蒙1001小米鸿蒙,小米高管早就放下狠话!愿意使用鸿蒙2.0系统:那其他厂商呢?...

【9月14日讯】相信大家都知道&#xff0c;自从华为鸿蒙OS系统2.0版本正式发布以后&#xff0c;由于华为消费者业务CEO余承东正式确认&#xff1a;“华为手机在12月开始适配鸿蒙OS系统&#xff0c;明年所有华为手机全面启用鸿蒙OS系统。” 这也意味着国产智能手机厂商也将彻底的…