在Scrapy中通过身份验证的会话进行爬网
在上一个问题中,我对问题不是很具体(希望通过与Scrapy进行身份验证的会话进行爬取),希望能够从更笼统的答案中得出解决方案。我应该宁可使用这个词crawling
。
因此,这是到目前为止的代码:
class MySpider(CrawlSpider):
name = 'myspider'
allowed_domains = ['domain.com']
start_urls = ['http://www.domain.com/login/']
rules = (
Rule(SgmlLinkExtractor(allow=r'-\w+.html$'), callback='parse_item', follow=True),
)
def parse(self, response):
hxs = HtmlXPathSelector(response)
if not "Hi Herman" in response.body:
return self.login(response)
else:
return self.parse_item(response)
def login(self, response):
return [FormRequest.from_response(response,
formdata={'name': 'herman', 'password': 'password'},
callback=self.parse)]
def parse_item(self, response):
i['url'] = response.url
# ... do more things
return i
如您所见,我访问的第一页是登录页面。如果尚未通过身份验证(在parse
函数中),则调用自定义login
函数,该函数将发布到登录表单中。然后,如果我
我 验证,我想继续爬行。
问题是parse
我尝试覆盖以登录的功能,现在不再进行必要的调用以刮擦任何其他页面(我假设)。而且我不确定如何保存我创建的项目。
有人做过这样的事吗?(使用进行身份验证,然后进行爬网CrawlSpider
)任何帮助将不胜感激。
-
请勿在中覆盖
parse
函数CrawlSpider
:使用时
CrawlSpider
,您不应覆盖此parse
功能。这里的CrawlSpider
文档中有一个警告:http
:
//doc.scrapy.org/en/0.14/topics/spiders.html#scrapy.contrib.spiders.Rule这是因为使用
CrawlSpider
,parse
(任何请求的默认回调)都将发送要由Rule
s处理的响应。
爬网之前登录:
为了在Spider开始抓取之前进行某种初始化,您可以使用
InitSpider
(继承自CrawlSpider
),并覆盖该init_request
函数。蜘蛛初始化时以及开始爬行之前,将调用此函数。为了让Spider开始抓取,您需要致电
self.initialized
。您可以在
此处
阅读对此负责的代码(它具有有用的文档字符串)。
一个例子:
from scrapy.contrib.spiders.init import InitSpider from scrapy.http import Request, FormRequest from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.contrib.spiders import Rule class MySpider(InitSpider): name = 'myspider' allowed_domains = ['example.com'] login_page = 'http://www.example.com/login' start_urls = ['http://www.example.com/useful_page/', 'http://www.example.com/another_useful_page/'] rules = ( Rule(SgmlLinkExtractor(allow=r'-\w+.html$'), callback='parse_item', follow=True), ) def init_request(self): """This function is called before crawling starts.""" return Request(url=self.login_page, callback=self.login) def login(self, response): """Generate a login request.""" return FormRequest.from_response(response, formdata={'name': 'herman', 'password': 'password'}, callback=self.check_login_response) def check_login_response(self, response): """Check the response returned by a login request to see if we are successfully logged in. """ if "Hi Herman" in response.body: self.log("Successfully logged in. Let's start crawling!") # Now the crawling can begin.. return self.initialized() else: self.log("Bad times :(") # Something went wrong, we couldn't log in, so nothing happens. def parse_item(self, response): # Scrape data from page
保存项目:
您的Spider返回的项目将传递到管道,该管道负责执行您想对数据进行的任何处理。我建议您阅读文档:http : //doc.scrapy.org/en/0.14/topics/item-
pipeline.html如果您有关于
Item
s的任何问题/疑问,请随时打开一个新问题,我们将尽最大努力为您提供帮助。