【问题标题】:Pull adjacent table cell using BeautifulSoup Python使用 BeautifulSoup Python 拉取相邻的表格单元格
【发布时间】:2016-02-19 17:42:50
【问题描述】:
table = plan1.find('table', id = 'planComparison')
pcp = table.findChildren(text=' Doctor Visit - Primary Care ')
我已使用上述代码将 pcp 变量设置为显示“就诊 - 初级保健”的单元格。我需要它旁边的单元格中的信息(它会因情况而异)。
如何拉出相邻的单元格?有没有办法返回 pcp 变量单元格的行号?任何意见表示赞赏。
Source url
【问题讨论】:
标签:
python
web-scraping
beautifulsoup
html-table
【解决方案1】:
要获取下一个td,请使用nextSibling 函数。这可能有点棘手,因为空格可以被认为是下一个兄弟,所以你必须尝试一些事情。我将您的代码修改为:
table = plan1.find('table', id = 'planComparison')
pcp = table.find('td',text=' Doctor Visit - Primary Care ')
print(pcp.nextSibling.nextSibling.text)
输出是:
Copay: No Charge after deductible; Coinsurance: No Charge after deductible
请注意,我必须调用 nextSibling 两次才能到达您想要的 td 标签,然后调用 text 才能删除 <td> 标签。
另请注意,我指定您希望在 find 中使用 td,而不是一般的 findChildren。