gpt4 book ai didi

python - Beautifulsoup 在表中获取值

转载 作者:太空宇宙 更新时间:2023-11-04 07:13:08 24 4
gpt4 key购买 nike

我正在尝试抓取 http://www.co.jefferson.co.us/ats/displaygeneral.do?sch=000104并获得“所有者姓名”我有什么工作但真的很难看而且不是我确定的最好的,所以我正在寻找更好的方法。这是我所拥有的:

soup = BeautifulSoup(url_opener.open(url))            
x = soup('table', text = re.compile("Owner Name"))
print 'And the owner is', x[0].parent.parent.parent.tr.nextSibling.nextSibling.next.next.next

相关的 HTML 是

<td valign="top">
<table border="1" cellpadding="1" cellspacing="0" align="right">
<tbody><tr class="tableheaders">
<td>Owner Name(s)</td>
</tr>

<tr>

<td>PILCHER DONALD L </td>
</tr>

</tbody></table>
</td>

哇,有很多关于 beautifulsoup 的问题,我浏览了它们,但没有找到对我有帮助的答案,希望这不是重复的问题

最佳答案

(编辑:显然 OP 发布的 HTML 是谎言——实际上没有要查找的 tbody 标签,尽管他强调要包含在那个 HTML。所以,更改为使用 table 而不是 tbody)。

由于您可能需要多个表行(例如,查看您提供的行的同级 URL,最后一位数字 4 更改为 5),我建议使用如下循环:

# locate the table containing a cell with the given text
owner = re.compile('Owner Name')
cell = soup.find(text=owner).parent
while cell.name != 'table': cell = cell.parent
# print all non-empty strings in the table (except for the given text)
for x in cell.findAll(text=lambda x: x.strip() and not owner.match(x)):
print x

这对于页面结构中的微小变化相当稳健:找到感兴趣的单元格后,它循环其父级直到找到表格标记,然后遍历该表格中非空(或只是空白)的所有可导航字符串),不包括 owner header 。

关于python - Beautifulsoup 在表中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1817184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com