[英]How to write scraped data into a CSV file in Scrapy?
我试图通过提取子链接及其标题来抓取网站,然后将提取的标题及其相关链接保存到CSV文件中。 我运行以下代码,创建了CSV文件,但它为空。 有什么帮助吗?
我的Spider.py文件如下所示:
from scrapy import cmdline
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
class HyperLinksSpider(CrawlSpider):
name = "linksSpy"
allowed_domains = ["some_website"]
start_urls = ["some_website"]
rules = (Rule(LinkExtractor(allow=()), callback='parse_obj', follow=True),)
def parse_obj(self, response):
items = []
for link in LinkExtractor(allow=(), deny=self.allowed_domains).extract_links(response):
item = ExtractlinksItem()
for sel in response.xpath('//tr/td/a'):
item['title'] = sel.xpath('/text()').extract()
item['link'] = sel.xpath('/@href').extract()
items.append(item)
return items
cmdline.execute("scrapy crawl linksSpy".split())
我的pipelines.py是:
import csv
class ExtractlinksPipeline(object):
def __init__(self):
self.csvwriter = csv.writer(open('Links.csv', 'wb'))
def process_item(self, item, spider):
self.csvwriter.writerow((item['title'][0]), item['link'][0])
return item
我的items.py是:
import scrapy
class ExtractlinksItem(scrapy.Item):
# define the fields for your item here like:
title = scrapy.Field()
link = scrapy.Field()
pass
我还更改了settings.py:
ITEM_PIPELINES = {'extractLinks.pipelines.ExtractlinksPipeline': 1}
要输出所有scrapy数据,其内置功能称为Feed Exports 。
FEED_FORMAT
您需要做的是settings.py
文件中的两个设置: FEED_FORMAT
-Feed的保存格式(在您的情况下为csv)和FEED_URI
-Feed的保存位置,例如~/my_feed.csv
我的相关答案包括一个用例:
https://stackoverflow.com/a/41473241/3737009
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.