我正在创建一个简单的scrapy项目,以便更好地理解如何使用它,我打算做的是抓取StackOverflow的问题页面。
我的蜘蛛被称为first
,这里是文件的内容。
# -*- coding: utf-8 -*-
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class FirstSpider(CrawlSpider):
name = 'first'
allowed_domains = ['stackoverflow.com']
start_urls = ['https://stackoverflow.com/questions']
rules = (
Rule(LinkExtractor(allow=['/questions/\?page=\d&sort=newest']), callback='parse_item', follow=True),
)
def parse_item(self, response):
item = scrapy.Item()
selector_list = response.css('.question-summary')
for selector in selector_list:
item['question'] = selector.css('h3 a::text').extract()
item['votes'] = selector.css('.vote-count-post strong::text').extract()
item['answers'] = selector.css('.status strong::text').extract()
item['views'] = selector.css('.views::text').extract()
item['username'] = selector.css('.user-details a::text').extract()
item['user-link'] = selector.css('.user-details a::attr(href)').extract()
return item
然后它应该遍历收集信息的问题的页面。
我可以从shell获取数据,但在尝试抓取或保存输出时失败。
这是scrapy crawl first
的输出:
2018-04-07 13:57:06 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: scraper)
2018-04-07 13:57:06 [scrapy.utils.log] INFO: Versions: lxml 4.2.1.0, libxml2 2.9 .5, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted 17.9.0, Python 2.7.14 ( v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)], pyOpenSS L 17.5.0 (OpenSSL 1.1.0h 27 Mar 2018), cryptography 2.2.2, Platform Windows-XP- 5.1.2600-SP3
2018-04-07 13:57:06 [scrapy.crawler] INFO: Overridden settings: {'NEWSPIDER_MODU LE': 'scraper.spiders', 'SPIDER_MODULES': ['scraper.spiders'], 'ROBOTSTXT_OBEY': True, 'BOT_NAME': 'scraper'}
2018-04-07 13:57:06 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.logstats.LogStats',
'scrapy.extensions.telnet.TelnetConsole',
'scrapy.extensions.corestats.CoreStats']
2018-04-07 13:57:07 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
'scrapy.downloadermiddlewares.retry.RetryMiddleware',
'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
'scrapy.downloadermiddlewares.stats.DownloaderStats']
2018-04-07 13:57:07 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
'scrapy.spidermiddlewares.referer.RefererMiddleware',
'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
'scrapy.spidermiddlewares.depth.DepthMiddleware']
2018-04-07 13:57:07 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2018-04-07 13:57:07 [scrapy.core.engine] INFO: Spider opened
2018-04-07 13:57:07 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pag es/min), scraped 0 items (at 0 items/min)
2018-04-07 13:57:07 [scrapy.extensions.telnet] DEBUG: Telnet console listening o n 127.0.0.1:6023
2018-04-07 13:57:08 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://stackoverflow.com/robots.txt> (referer: None)
2018-04-07 13:57:09 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://stackoverflow.com/questions> (referer: None)
2018-04-07 13:57:09 [scrapy.core.engine] INFO: Closing spider (finished)
2018-04-07 13:57:09 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 502,
'downloader/request_count': 2,
'downloader/request_method_count/GET': 2,
'downloader/response_bytes': 35092,
'downloader/response_count': 2,
'downloader/response_status_count/200': 2,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2018, 4, 7, 10, 57, 9, 609000),
'log_count/DEBUG': 3,
'log_count/INFO': 7,
'response_received_count': 2,
'scheduler/dequeued': 1,
'scheduler/dequeued/memory': 1,
'scheduler/enqueued': 1,
'scheduler/enqueued/memory': 1,
'start_time': datetime.datetime(2018, 4, 7, 10, 57, 7, 625000)}
2018-04-07 13:57:09 [scrapy.core.engine] INFO: Spider closed (finished)
答案 0 :(得分:1)
项目字段应在items.py
中定义,如此处所述(否则会有KeyError
):https://doc.scrapy.org/en/latest/topics/items.html#declaring-items。
在您的情况下,需要在循环内(不在外部)创建和生成项目。像:
for selector in selector_list:
item = QuestionItem()
item['question'] = selector.css('h3 a::text').get()
...
yield item
另外,请考虑使用项目加载器来填充项目:https://doc.scrapy.org/en/latest/topics/loaders.html