[英]scrapy crawlspider output
我在Scrapy文檔中的CrawlSpider示例中遇到問題。 似乎可以正常爬行,但是我很難將其輸出到CSV文件(或其他任何東西)。
所以,我的問題是我可以使用這個:
scrapy crawl dmoz -o items.csv
還是我必須創建一個物料管道 ?
更新,現在有代碼!:
import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
from targets.item import TargetsItem
class MySpider(CrawlSpider):
name = 'abc'
allowed_domains = ['ididntuseexample.com']
start_urls = ['http://www.ididntuseexample.com']
rules = (
# Extract links matching 'category.php' (but not matching 'subsection.php')
# and follow links from them (since no callback means follow=True by default).
Rule(LinkExtractor(allow=('ididntuseexample.com', ))),
)
def parse_item(self, response):
self.log('Hi, this is an item page! %s' % response.url)
item = TargetsItem()
item['title'] = response.xpath('//h2/a/text()').extract() #this pulled down data in scrapy shell
item['link'] = response.xpath('//h2/a/@href').extract() #this pulled down data in scrapy shell
return item
規則是CrawlSpider
用於以下鏈接的機制。 這些鏈接是用LinkExtractor
定義的。 該元素基本上指示要從爬網頁面提取的鏈接(如start_urls
列表中定義的鏈接)。 然后,您可以傳遞一個回調,該回調將在每個提取的鏈接上或更確切地說在這些鏈接之后下載的頁面上調用。
您的規則必須調用parse_item
。 因此,請替換:
Rule(LinkExtractor(allow=('ididntuseexample.com', ))),
與:
Rule(LinkExtractor(allow=('ididntuseexample.com',)), callback='parse_item),
此規則定義要調用parse_item
,其每一個環節上href
是ididntuseexample.com
。 我懷疑您要作為鏈接提取器的不是域,而是您要關注/抓取的鏈接。
在這里,您有一個基本示例,可檢索Hacker News來檢索主頁中所有新聞的標題和第一條評論的第一行。
import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
class HackerNewsItem(scrapy.Item):
title = scrapy.Field()
comment = scrapy.Field()
class HackerNewsSpider(CrawlSpider):
name = 'hackernews'
allowed_domains = ['news.ycombinator.com']
start_urls = [
'https://news.ycombinator.com/'
]
rules = (
# Follow any item link and call parse_item.
Rule(LinkExtractor(allow=('item.*', )), callback='parse_item'),
)
def parse_item(self, response):
item = HackerNewsItem()
# Get the title
item['title'] = response.xpath('//*[contains(@class, "title")]/a/text()').extract()
# Get the first words of the first comment
item['comment'] = response.xpath('(//*[contains(@class, "comment")])[1]/font/text()').extract()
return item
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.