在我的previous question中,我对我的问题(用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
函数,该函数将发布到登录表单。然后,如果我am经过身份验证,我想继续爬行。
问题是我试图重写的parse
函数为了登录,现在不再进行必要的调用来刮除任何进一步的页面(我假设)。我不知道如何保存我创建的项目。
以前有人做过这样的事吗?(使用CrawlSpider
进行身份验证,然后进行爬网)如有任何帮助,将不胜感激。
为了使上面的解决方案能够工作,我必须使crawpsider从InitSpider继承,而不再从BaseSpider继承,方法是在不完整的源代码上更改以下内容。在scrapy/contrib/spiders/crawl.py文件中:
from scrapy.contrib.spiders.init import InitSpider
class CrawlSpider(BaseSpider)
更改为class CrawlSpider(InitSpider)
否则蜘蛛就不会调用
init_request
方法。还有其他更简单的方法吗?
不要重写
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的代码(它有有用的docstring)。
示例:
保存项目:
Spider返回的项将被传递到负责对数据执行任何操作的管道。我建议您阅读文档:http://doc.scrapy.org/en/0.14/topics/item-pipeline.html
如果您在
Item
方面有任何问题,请毫不犹豫地弹出一个新问题,我将尽力帮助您。如果您需要的是Http认证,请使用提供的中间件钩子。
在
settings.py
中在您的
spider class
中添加属性相关问题 更多 >
编程相关推荐