【问题标题】:HTML tables with python beautiful soup带有python美丽汤的HTML表格
【发布时间】:2015-03-27 22:07:57
【问题描述】:

我有一个如下所示的 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>

我正在使用 Beautiful soup 来提取特定数据,这些数据是来自一个爬虫蜘蛛的响应

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>

这种特殊情况不适用于以下同级搜索?如何克服?

【问题讨论】:

    标签: python html beautifulsoup html-parsing scrapy


    【解决方案1】:

    您可以找到td 元素by text 并获取next sibling

    table.find('td', text='Manifold Type').next_sibling.text
    

    附带说明一下,为什么需要在 Scrapy 蜘蛛中使用 BeautifulSoupScrapy 本身在 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']
    

    【讨论】:

    • @Alecxe ..scrapy xpath 解决方案就像一个魅力..但是..参见编辑..我有一个表,其中下一个兄弟是 href ..在这些情况下我得到一个空白结果..在这种情况下,我怎样才能获得文本 essar shipping..
    • @Amistad 很好,//table[@class="form"]//td[.="Manifold Type"]/following-sibling::td/a/text() 应该可以解决问题。
    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 2021-04-03
    相关资源
    最近更新 更多