在我的previous question ,我对我的问题不是很具体(使用经过身份验证的 Scrapy session 进行抓取),希望能够从更一般的答案中推断出解决方案。我可能宁愿使用 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
进行身份验证,然后抓取)任何帮助将不胜感激。
最佳答案
不要覆盖 CrawlSpider
中的 parse
函数:
当您使用 CrawlSpider
时,不应覆盖 parse
函数。 CrawlSpider
文档中有一个警告:http://doc.scrapy.org/en/0.14/topics/spiders.html#scrapy.contrib.spiders.Rule
这是因为使用 CrawlSpider
,parse
(任何请求的默认回调)发送要由 Rule
处理的响应.
在抓取前登录:
为了在蜘蛛开始爬行之前进行某种初始化,您可以使用 InitSpider
(继承自 CrawlSpider
),并覆盖 init_request
函数。该函数将在蜘蛛初始化时和开始爬行之前调用。
为了让蜘蛛开始爬行,你需要调用self.initialized
。
您可以阅读负责此 here 的代码(它有有用的文档字符串)。
一个例子:
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
有任何问题/疑问,请随时提出新问题,我会尽力提供帮助。
关于python - 在 Scrapy 中使用经过身份验证的 session 进行爬网,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5851213/