python - HTML 表格与 python 美丽汤

标签 python html beautifulsoup html-parsing scrapy

我有一个 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 来提取来自 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>

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

最佳答案

您可以找到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']

关于python - HTML 表格与 python 美丽汤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28201896/

相关文章:

python - 如何使用 os.posix_fadvise 防止 Linux 上的文件缓存?

python - 如何在Golang中将这些(十六进制)数字转换为字符?

JavaScript 函数无法从 HTML 文本区域检索字符串

python - 如何漂亮地打印 BeautifulSoup 的字符串输出

python - 为什么 "B"不等于 "B"?

python - 如何删除字符串中的字母

html - CSS 文本对齐 - 为什么我的段落文本没有按照我的需要对齐,而标题却可以?

javascript - 从上层元素中移除元素类

python - 如何使用replace_with避免在BeautifulSoup中打印utf-8字符

python - 我如何使用beautifulsoup解析文本中包含内部标签的html字符串