【问题标题】:Python: Scrapy spider doesn't return results?Python:Scrapy spider 不返回结果?
【发布时间】:2015-04-24 16:49:27
【问题描述】:

我知道我需要处理我的选择器以调整更具体的数据,但我不知道为什么我的 csv 是 EMPTY。

我的解析类:

class MySpider(BaseSpider):
    name =  "wikipedia"
    allowed_domains = ["en.wikipedia.org/"]
    start_urls = ["http://en.wikipedia.org/wiki/2014_in_film"]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        titles = hxs.select('//table[@class="wikitable sortable jquery-tablesorter"], [@style="margin:auto; margin:auto;"]')
        items = []
        for title in titles:
            item = WikipediaItem()
            item["title"] = title.select("td/text()").extract()
            item["url"] = title.select("a/text()").extract()
            items.append(item)
        return items

我正在尝试抓取的 html:

<table class="wikitable sortable" style="margin:auto; margin:auto;">
<caption>Highest-grossing films of 2014</caption>
<tr>
<th>Rank</th>
<th>Title</th>
<th>Studio</th>
<th>Worldwide gross</th>
</tr>
<tr>
<th style="text-align:center;">1</th>
<td><i><a href="/wiki/Transformers:_Age_of_Extinction" title="Transformers: Age of Extinction">Transformers: Age of Extinction</a></i></td>
<td><a href="/wiki/Paramount_Pictures" title="Paramount Pictures">Paramount Pictures</a></td>
<td>$1,091,404,499</td>
</tr>

html 中的这一部分在每部电影中一遍又一遍地重复,所以一旦正确选择它就应该抓取所有内容:

    <tr>
    <th style="text-align:center;">1</th>
    <td><i><a href="/wiki/Transformers:_Age_of_Extinction" title="Transformers: Age of Extinction">Transformers: Age of Extinction</a></i></td>
    <td><a href="/wiki/Paramount_Pictures" title="Paramount Pictures">Paramount Pictures</a></td>
    <td>$1,091,404,499</td>
    </tr>

我知道问题不在于导出,因为即使在我的 shell 中,它也会显示“抓取 0 个页面,抓取 0 个项目”,所以实际上没有任何内容被触及。

【问题讨论】:

  • 关于选择器,我不知道需要多少具体,所以这很可能是我的错误。

标签: python parsing csv scrapy selector


【解决方案1】:
  1. 表格不是可重复元素...它是表格行。

  2. 您需要更改代码以选择表格行,即

    titles = hxs.select('//tr')
    
  3. 然后遍历它们并使用 xpath 获取您的数据

    for title in titles:
        item = WikipediaItem()
        item["title"] = title.xpath("./td/i/a/@title")[0]
        item["url"] = title.xpath("./td/i/a/@href")[0]
        items.append(item)
    

【讨论】:

  • 我怎么能只抓取文本(就像正常的 td/text().......),因为我不能完全做到:item["title"] = title.xpath ("./td/i/a/[@title]/text()").extract()
  • 参见上面的更正...基本上 xpath 输出一个列表,因此索引 0 应该为您提供文本...不需要提取
猜你喜欢
  • 2016-12-14
  • 1970-01-01
  • 2017-12-12
  • 2012-09-24
  • 2019-06-18
  • 2020-04-05
  • 2018-03-19
  • 2011-07-17
  • 2015-09-29
相关资源
最近更新 更多