我有一个HTML表格,如下所示:
<table border=0 cellspacing=1 cellpadding=2 class=form>
<tr class=form><td class=formlabel>Heating Coils in Bunker Tanks</td><td class=form>N</td></tr>
<tr class=forma><td class=formlabel>Heating Coils in Cargo Tanks</td><td class=form>U</td></tr>
<tr class=form><td class=formlabel>Manifold Type</td><td class=form>N</td></tr>
<tr class=forma><td class=formlabel>No. Holds</td><td class=form>5</td></tr>
<tr class=form><td class=formlabel>No. Centreline Hatches</td><td class=form>5</td></tr>
<tr class=forma><td class=formlabel>Lifting Gear</td><td class=form>Yes</td></tr>
<tr class=form><td class=formlabel>Gear</td><td class=form>4 Crane (30.5t SWL)</td></tr>
<tr class=forma><td class=formlabel>Alteration</td><td class=form>Unknown</td></tr>
</table>
我正在使用美丽的汤来提取特定数据,这些数据来自scrapy蜘蛛
soup = BeautifulSoup(response.body_as_unicode())
table= soup.find('table', {'class': 'form'})
# psusedo code find manifold type and number of Holds
如何执行此操作。请注意,值的排序可能会更改,但表单标签始终保持不变?如何使用特定表格标签进行搜索?
<tr class=forma><td class=formlabel>Fleet Manager (Operator)</td><td class=form><a href="oBasic.asp?LRNumber=9442964&Action=Display&LRCompanyNumber=40916">ESSAR SHIPPING LTD</a></td></tr>
这种特殊情况不适用于以下兄弟搜索?如何克服这个?
答案 0 :(得分:1)
您可以找到td
元素by text并获取next sibling:
table.find('td', text='Manifold Type').next_sibling.text
作为旁注,为什么需要在Scrapy蜘蛛中使用BeautifulSoup
? Scrapy
本身在HTML解析,定位元素方面非常强大:
response.xpath('//table[@class="form"]//td[.="Manifold Type"]/following-sibling::td/text()')
来自scrapy shell
:
$ scrapy shell index.html
In [1]: response.xpath('//table[@class="form"]//td[.="Manifold Type"]/following-sibling::td/text()').extract()
Out[1]: [u'N']