【发布时间】:2017-05-21 11:49:21
【问题描述】:
我正在尝试通过提取子链接及其标题来抓取网站,然后将提取的标题及其相关链接保存到 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}
【问题讨论】:
标签: python csv web-scraping scrapy web-crawler