登录到我自己的帐户后,我正在尝试从 stackoverflow 网站上抓取问题和发布日期。这是为了练习scrapy with splash。
成功登录我的帐户后,我可以访问问题页面。但是,我在数据提取过程中卡住了。我已经使用爬虫来管理提取,但它抛出了一个错误:
NotImplementedError:未定义 StackdataSpider.parse 回调
这是我到目前为止的进展:
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy_splash import SplashRequest
from scrapy.utils.response import open_in_browser
#docker run -it -p 8050:8050 --rm scrapinghub/splash
class StackdataSpider(CrawlSpider):
name = 'stackData'
allowed_domains = ['stackoverflow.com']
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36"
script='''
function main(splash, args)
splash.private_mode_enabled = false
url=args.url
assert(splash:go(url))
splash:set_viewport_full()
assert(splash:wait(1))
email_box = assert(splash:select("#email"))
email_box:focus()
email_box:send_text("test@test.com")
assert(splash:wait(1))
password_box = assert(splash:select("#password"))
password_box:focus()
password_box:send_text("testpassword")
assert(splash:wait(1))
submit_button = assert(splash:select("#submit-button"))
submit_button:mouse_click()
assert(splash:wait(5))
user_profile = assert(splash:select("a[href $='gopal-kisi']"))
user_profile:mouse_click()
assert(splash:wait(5))
questions_summary = assert(splash:select("a[href $='tab=questions']"))
questions_summary:mouse_click()
assert(splash:wait(5))
return splash:html()
end
'''
def start_requests(self):
yield SplashRequest(
url="https://stackoverflow.com/users/login",
headers={
'User-Agent':self.user_agent
},
callback=self.parse,
endpoint="execute",
args={
'lua_source':self.script
}
)
rules = (
Rule(LinkExtractor(restrict_xpaths="//a[@class='question-hyperlink']"),
callback='parse_item', follow=True, process_request="set_user_agent"),
)
def set_user_agent(self,request):
request.headers['User-Agent']=self.user_agent
return request
def parse_item(self, response):
yield {
'questions':response.xpath("//a[@class='question-hyperlink']/text()").get(),
'asked_date':response.xpath("(//span[@class='relativetime'])[1]/text()").get()
}
从我目前了解到的情况来看,当我们使用 start_requests 函数时,不需要使用 parse 函数。但是,如果我重命名要解析的 parse_item,它只会提取一个问题而不会出现任何错误。
这是错误的,因为它破坏了爬虫,并从响应页面给出了响应页面的结果,该响应页面由飞溅给出。我不希望那样。
我认为,这是与 crawlspider 一起飞溅的问题,但我不确定,即使我的猜测是正确的,我也不知道它是什么以及如何解决它。