【问题标题】:I'm trying to output my scrapy results to a csv file, but my output is always blank我正在尝试将我的 scrapy 结果输出到 csv 文件,但我的输出始终为空白
【发布时间】:2014-02-26 19:16:08
【问题描述】:

这是我的主要蜘蛛 bathuni.py

from scrapy.spider import Spider
from scrapy.selector import Selector
from bathUni.items import BathuniItem

class bathuni(Spider):
    name = "bathU"
    allowed_domains = ["http://international.southwales.ac.uk/"]
    start_urls= ["http://international.southwales.ac.uk/country/argentina/en/",
                 "http://international.southwales.ac.uk/country/france/en/",
                 "http://international.southwales.ac.uk/country/australia/en/"]

    def parse(self, response):
        sel = Selector(response)
        sites = sel.xpath('//div[@class="factsheet"]/ul/li')
        for site in sites:
            country = site.xpath('text()').extract()
            return country

我的 items.py 如下

from scrapy.item import Item, Field

class BathuniItem(Item):
    Country = Field()

我用来输出到 csv 文件的命令是

scrapy crawl bathU -o countries.csv -t csv

我的输出文件总是空的。任何帮助,将不胜感激。谢谢。

【问题讨论】:

    标签: python csv cmd scrapy


    【解决方案1】:

    将return country 更改为yield BathuniItem(Country=country)

    这解决了两个问题:

    1. ERROR: Spider must return Request, BaseItem or None, got 'unicode'
    2. 使用 yield 返回一个 python 生成器 - 来自一个函数的多个项目

    【讨论】:

    • 非常感谢,这正是我想要的。我想知道您是否有可能告诉我在抓取数据时如何更具体,而不仅仅是 /ul/li/ 我不希望网页上的所有 /ul/li 都只是一些特定的,有吗一种通过他们的 css 抓取它们的方法?
    • 你的 xpath 似乎使用了 div 类,所以我想你知道 xpath 的强大之处,尝试谷歌搜索更多 xpath 示例,它是一个非常强大的工具
    • 哇,这为我和我的项目打开了许多大门,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2015-06-03
    • 2013-07-04
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多