Python 如何以正确的格式将刮取的数据导出到csv文件?
我根据@paultrmbrth的建议对代码进行了改进。我需要的是从类似于和的页面中刮取数据,我希望csv输出如下图所示 但我的代码的csv输出有点混乱,如下所示: 我有两个问题,csv输出是否可以像第一张图片一样?我的第二个问题是,我想把电影标题也删掉,请给我一个提示或者给我一个代码,我可以用它删掉电影标题和内容 更新Python 如何以正确的格式将刮取的数据导出到csv文件?,python,csv,web-scraping,scrapy,Python,Csv,Web Scraping,Scrapy,我根据@paultrmbrth的建议对代码进行了改进。我需要的是从类似于和的页面中刮取数据,我希望csv输出如下图所示 但我的代码的csv输出有点混乱,如下所示: 我有两个问题,csv输出是否可以像第一张图片一样?我的第二个问题是,我想把电影标题也删掉,请给我一个提示或者给我一个代码,我可以用它删掉电影标题和内容 更新 塔伦·拉尔瓦尼完美地解决了这个问题。但是现在,csv文件的头只包含第一个刮取的url类别。例如,当我尝试刮取具有引用、在中引用、功能、在中特色和在类别中欺骗的,以及具有跟随、跟
塔伦·拉尔瓦尼完美地解决了这个问题。但是现在,csv文件的头只包含第一个刮取的url类别。例如,当我尝试刮取具有<代码>引用、在中引用、功能、在中特色和在<代码>类别中欺骗的,以及具有<代码>跟随、跟随、编辑自、编辑成、衍生、引用、在中引用、功能、在中特色的,在类别中欺骗和欺骗然后csv输出文件头将只包含第一个网页的类别,即中引用的引用、功能、特色和欺骗中,因此第二个网页中的某些类别,如如下所示,然后是,编辑自,编辑成和伪造的不会出现在输出csv文件头上,其内容也不会出现在输出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_EXPORTERS = {
'csv': '<yourproject>.exporters.NewLineRowCsvItemExporter',
}
要设置csv数据格式,最简单的方法之一是使用excel power查询清理数据,请执行以下步骤:
1:在excel中打开csv文件。
2:使用ctrl+A选择所有值
3:然后单击“插入并创建表格”中的表格。
4:创建表格后,单击顶部菜单中的数据并从表5中选择:知道他们打开了新的excel窗口电源查询。
6:选择任意列并单击拆分列
7:从拆分列中按分隔符选择,
8:知道逗号、空格等选择分隔符
9:最后一步选择高级选项,其中有两个选项按行或列拆分
10:您可以使用这些电源查询执行所有类型的数据清理这是根据您的需要设置数据格式的最简单方法请一次只问一个问题,否则答案和注释会混淆。您需要添加更多代码,以便我们了解您的错误所在,让我们也能重现您当前的问题。@TarunLalwani谢谢,效果很好!但是这些行只包含引用中的标题欺骗,后面是,这给了我一个错误:UnicodeEncodeError:“ascii”编解码器无法使用python或python3对位置2的字符u'\xf3'进行编码:序号不在范围(128)内?如果您使用的是Python,请尝试使用Python 32@TarunLalwani我更新了问题。如果可以,请帮助我。
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']