1

我正在尝试抓取 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 的问题,我浏览了它们,但没有找到对我有帮助的答案,希望这不是重复的问题

4

3 回答 3

5

编辑:显然 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

于 2009-11-30T00:36:16.080 回答
3

这是来自 Beautifulsoup 讨论组的 Aaron DeVore 的回答,它对我很有效。

soup = BeautifulSoup(...)
label = soup.find(text="Owner Name(s)")

需要 Tag.string 才能获得实际的名称字符串

name = label.findNext('td').string

如果您正在做一堆,您甚至可以进行列表理解。

names = [unicode(label.findNext('td').string) for label in
soup.findAll(text="Owner Name(s)")]
于 2009-11-30T20:23:16.310 回答
1

这是一个小小的进步,但我想不通如何摆脱三个父母。

x[0].parent.parent.parent.findAll('td')[1].string
于 2009-11-30T00:08:25.480 回答