scrapy+selenium+chrome實(shí)現(xiàn)模擬登入 附帶防反爬蟲方法

心塞的一天 廢話不多說直接上圖 代碼存放在github 地址:https://github.com/zhangshier/scrapy-


查看他登入的網(wǎng)址


?企查查 ? 地址 www.qichacha.com/user_login?

1.創(chuàng)建爬蟲

scrapy startproject qichacha ?創(chuàng)建爬蟲文件

cd qichacha?

scrapy genspider qicha 創(chuàng)建爬蟲

創(chuàng)建middlewares.py文件

代碼:

# -*- coding: utf-8 -*-

# Define here the models for your spider middleware

#

# See documentation in:

# http://doc.scrapy.org/en/latest/topics/spider-middleware.html

fromscrapyimportsignals

importrandom

fromscrapy.confimportsettings

classMiddlewaretestSpiderMiddleware(object):

# Not all methods need to be defined. If a method is not defined,

# scrapy acts as if the spider middleware does not modify the

# passed objects.

@classmethod

deffrom_crawler(cls,crawler):

# This method is used by Scrapy to create your spiders.

s = cls()

crawler.signals.connect(s.spider_opened,signal=signals.spider_opened)

returns

defprocess_spider_input(response,spider):

# Called for each response that goes through the spider

# middleware and into the spider.

# Should return None or raise an exception.

returnNone

defprocess_spider_output(response,result,spider):

# Called with the results returned from the Spider, after

# it has processed the response.

# Must return an iterable of Request, dict or Item objects.

foriinresult:

yieldi

defprocess_spider_exception(response,exception,spider):

# Called when a spider or process_spider_input() method

# (from other spider middleware) raises an exception.

# Should return either None or an iterable of Response, dict

# or Item objects.

pass

defprocess_start_requests(start_requests,spider):

# Called with the start requests of the spider, and works

# similarly to the process_spider_output() method, except

# that it doesn’t have a response associated.

# Must return only requests (not items).

forrinstart_requests:

yieldr

defspider_opened(self,spider):

spider.logger.info('Spider opened: %s'% spider.name)

#更換User-agent?

classUAMiddleware(object):

user_agent_list = settings['USER_AGENT_LIST']

defprocess_request(self,request,spider):

ua = random.choice(self.user_agent_list)

request.headers['User-Agent'] = ua

#反爬蟲 ?實(shí)現(xiàn)代理ip

classProxyMiddleware(object):

ip_list = settings['IP_LIST']

defprocess_request(self,request,spider):

ip = random.choice(self.ip_list)

request.meta['proxy'] = ip

fromseleniumimportwebdriver

fromscrapy.httpimportHtmlResponse

classJSPageMiddleware(object):

#通過chrome 動(dòng)態(tài)訪問

defprocess_request(self,request,spider):

ifspider.name =="qicha":

spider. browser.get(request.url)

importtime

time.sleep(3)

spider.browser.find_element_by_xpath('//div[@class="form-group has-feedback m-l-lg m-r-lg m-t-xs m-b-none"]/input[@name="nameNormal"]').send_keys("你自己的賬號(hào)")

spider.browser.find_element_by_xpath('//div[@class="form-group has-feedback m-l-lg m-r-lg m-t-xs m-b-none"]/input[@name="pwdNormal"]').send_keys("你自己的密碼")

time.sleep(9)

#spider.browser.find_element_by_xpath('//div[@class="m-l-lg m-r-lg m-t-lg"]/button[@class="btn? btn-primary? ? m-t-n-xs btn-block btn-lg font-15"]').click()

returnHtmlResponse(url=spider.browser.current_url,body=spider.browser.page_source,encoding="utf-8")

到spider 下的 qicha.py?

代碼

# -*- coding: utf-8 -*-

importscrapy

fromscrapy.httpimportFormRequest

fromseleniumimportwebdriver

fromscrapy.xlib.pydispatchimportdispatcher

fromscrapyimportsignals

classQichaSpider(scrapy.Spider):

name ="qicha"

allowed_domains = ["http://www.qichacha.com/"]

start_urls = ['http://www.qichacha.com/user_login']

def__init__(self):

self.browser = webdriver.Chrome(executable_path="C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe") ?# 與你自己的chromedrive位置相對

super(QichaSpider,self).__init__()

dispatcher.connect(self.spider_closed,signals.spider_closed)

defspider_closed(self,spider):

#當(dāng)爬蟲退出的時(shí)候 關(guān)閉chrome

print("spider closed")

# self.browser.quit()

defparse(self,response):

printresponse.body.decode

配置settings.py 用來存放代理ip ? 跟useragent

DOWNLOADER_MIDDLEWARES = {

'qichacha.middlewares.UAMiddleware':543, ?#用來更換useragent

'qichacha.middlewares.ProxyMiddleware':544,#用來更換代理ip

'qichacha.middlewares.JSPageMiddleware':540,#與,middlewares對應(yīng) 用來實(shí)現(xiàn)自動(dòng)登入

}

#user_agent

USER_AGENT_LIST = ['Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1',

'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36',

'Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11']

#代理ip

IP_LIST = ['http://175.155.25.19:80',

'http://124.88.67.19:80',

'http://110.72.32.103:8123',

'http://175.155.25.40:808',

'http://175.155.24.2:808']

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容