我有一个以下格式的html页面(seed)
:
<div class="sth1">
<table cellspacing="6" width="600">
<tr>
<td>
<a href="link1"><img alt="alt1" border="0" height="22" src="img1" width="92"></a>
</td>
<td>
<a href="link1">name1</a>
</td>
<td>
<a href="link2"><img alt="alt2" border="0" height="22" src="img2" width="92"></a>
</td>
<td>
<a href="link2">name2</a>
</td>
</tr>
</table>
</div>
我想要做的是循环所有<tr>
并使用python scrapy提取所有href, alt
对。在这个例子中,我应该得到:
link1, alt1
link2, alt2
答案 0 :(得分:1)
以下是Scrapy Shell
:
$ scrapy shell index.html
In [1]: for cell in response.xpath("//div[@class='sth1']/table/tr/td"):
...: href = cell.xpath("a/@href").extract()
...: alt = cell.xpath("a/img/@alt").extract()
...: print href, alt
[u'link1'] [u'alt1']
[u'link1'] []
[u'link2'] [u'alt2']
[u'link2'] []
其中index.html
包含问题中提供的示例HTML。
答案 1 :(得分:1)
您可以尝试使用Scrapy的内置SelectorList并结合Python的zip():
from scrapy.selector import SelectorList
xpq = '//div[@class="sth1"]/table/tr/td[./a/img]'
cells = SelectorList(response.xpath(xpq))
zip(cells.xpath('a/@href'), cells.xpath('a/img/@alt'))
=> [('link1', 'alt1'), ('link2', 'alt2')]