python – 如何以正确的格式将刮取的数据导出到csv文件?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 如何以正确的格式将刮取的数据导出到csv文件?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4360字,纯文字阅读大概需要7分钟。
内容图文
![python – 如何以正确的格式将刮取的数据导出到csv文件?](/upload/InfoBanner/zyjiaocheng/697/9865413a61414ca492b766f4b44ef4be.jpg)
根据@paultrmbrth的this建议,我对我的代码进行了改进.我需要的是从类似于this和this的页面中抓取数据,我希望csv输出如下图所示.
但我的代码的csv输出有点乱,像这样:
我有两个问题,无论如何,csv输出可能像第一张图片一样吗?而我的第二个问题是,我希望这部电影也要废弃,请给我一个提示或提供一个代码,我可以用来刮掉电影名称和内容.
UPDATE
Tarun Lalwani完美地解决了这个问题.但是现在,csv文件的标题只包含第一个已删除的网址类别.例如,当我尝试刮擦this webpage时,其中包含参考,参考,特征,精选和欺骗类别和this webpage,其中包含跟随,跟随,编辑,编辑,分拆,参考,参考,特征,精选in,Spoofs和Spoofed分类然后csv输出文件标题将只包含第一个网页的类别,参考,引用,功能,精选和欺骗,所以从第二个网页的一些类别,如跟随,跟随,编辑,编辑into和Spoofs将不在输出csv文件头上,所以它的内容.
这是我使用的代码:
import scrapy
class ExampleSpider(scrapy.Spider):
name = "example"
allowed_domains = ["imdb.com"]
start_urls = (
'http://www.imdb.com/title/tt0093777/trivia?tab=mc&ref_=tt_trv_cnn',
'http://www.imdb.com/title/tt0096874/trivia?tab=mc&ref_=tt_trv_cnn',
)
def parse(self, response):
item = {}
for cnt, h4 in enumerate(response.css('div.list > h4.li_group'), start=1):
item['Title'] = response.css("h3[itemprop='name'] a::text").extract_first()
key = h4.xpath('normalize-space()').get().strip()
if key in ['Follows', 'Followed by', 'Edited into', 'Spun-off from', 'Spin-off', 'Referenced in',
'Featured in', 'Spoofed in', 'References', 'Spoofs', 'Version of', 'Remade as', 'Edited from',
'Features']:
values = h4.xpath('following-sibling::div[count(preceding-sibling::h4)=$cnt]', cnt=cnt).xpath(
'string(.//a)').getall(),
item[key] = values
yield item
这是exporters.py文件:
try:
from itertools import zip_longest as zip_longest
except:
from itertools import izip_longest as zip_longest
from scrapy.exporters import CsvItemExporter
from scrapy.conf import settings
class NewLineRowCsvItemExporter(CsvItemExporter):
def __init__(self, file, include_headers_line=True, join_multivalued=',', **kwargs):
super(NewLineRowCsvItemExporter, self).__init__(file, include_headers_line, join_multivalued, **kwargs)
def export_item(self, item):
if self._headers_not_written:
self._headers_not_written = False
self._write_headers_and_set_fields_to_export(item)
fields = self._get_serialized_fields(item, default_value='',
include_empty=True)
values = list(self._build_row(x for _, x in fields))
values = [
(val[0] if len(val) == 1 and type(val[0]) in (list, tuple) else val)
if type(val) in (list, tuple)
else (val, )
for val in values]
multi_row = zip_longest(*values, fillvalue='')
for row in multi_row:
self.csv_writer.writerow([unicode(s).encode("utf-8") for s in row])
我想要实现的是我希望所有这些类别都在csv输出头上.
'Follows', 'Followed by', 'Edited into', 'Spun-off from', 'Spin-off', 'Referenced in',
'Featured in', 'Spoofed in', 'References', 'Spoofs', 'Version of', 'Remade as', 'Edited from', 'Features'
任何帮助,将不胜感激.
解决方法:
您可以使用以下提取标题
item = {}
item['Title'] = response.css("h3[itemprop='name'] a::text").extract_first()
对于CSV部分,您需要创建一个FeedExports,它可以将每行拆分成多行
from itertools import zip_longest
from scrapy.contrib.exporter import CsvItemExporter
class NewLineRowCsvItemExporter(CsvItemExporter):
def __init__(self, file, include_headers_line=True, join_multivalued=',', **kwargs):
super(NewLineRowCsvItemExporter, self).__init__(file, include_headers_line, join_multivalued, **kwargs)
def export_item(self, item):
if self._headers_not_written:
self._headers_not_written = False
self._write_headers_and_set_fields_to_export(item)
fields = self._get_serialized_fields(item, default_value='',
include_empty=True)
values = list(self._build_row(x for _, x in fields))
values = [
(val[0] if len(val) == 1 and type(val[0]) in (list, tuple) else val)
if type(val) in (list, tuple)
else (val, )
for val in values]
multi_row = zip_longest(*values, fillvalue='')
for row in multi_row:
self.csv_writer.writerow(row)
然后,您需要在设置中指定Feed导出器
FEED_EXPORTERS = {
'csv': '<yourproject>.exporters.NewLineRowCsvItemExporter',
}
假设您将代码放在exporters.py文件中.输出将是所需的
编辑-1
要设置字段及其顺序,您需要在settings.py中定义FEED_EXPORT_FIELDS
FEED_EXPORT_FIELDS = ['Title', 'Follows', 'Followed by', 'Edited into', 'Spun-off from', 'Spin-off', 'Referenced in',
'Featured in', 'Spoofed in', 'References', 'Spoofs', 'Version of', 'Remade as', 'Edited from',
'Features']
https://doc.scrapy.org/en/latest/topics/feed-exports.html#std:setting-FEED_EXPORT_FIELDS
内容总结
以上是互联网集市为您收集整理的python – 如何以正确的格式将刮取的数据导出到csv文件?全部内容,希望文章能够帮你解决python – 如何以正确的格式将刮取的数据导出到csv文件?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。