我知道我需要在我的选择器上工作才能调整更具体的数据,但我不知道为什么我的csv是空的。
我的解析类:
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 个项目",所以实际上什么都没有被触及。
-
该表不是可重复的元素...它是表格行。
-
您将需要更改代码以选择表行,即
titles = hxs.select('//tr')
-
然后遍历它们并使用 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)