Python:Scrapy 蜘蛛没有 return 结果?

Python: Scrapy spider doesn't return results?

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

我的解析 class:

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>,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>,091,404,499</td>
    </tr>

我知道问题不在于导出,因为即使在我的 shell 中它也显示 "Crawl 0 pages, Scraped 0 Items" 所以实际上什么都没有被触及。

  1. table 不是 repeatable 元素...它是 table 行。

  2. 您需要将代码更改为 select table 行,即

    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)