Skip to main content
 首页 » 编程设计

python之Beautifulsoup 在表中获取值

2025年05月04日13luoye11

我正在尝试抓取 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 。