【发布时间】:2017-11-03 13:26:46
【问题描述】:
我已经在 python 中编写了一个脚本来查找 td 标记中的文本,这是第一个 tdtag 的 next sibling,使用 BeautifulSoup 和 css 选择器。如果我运行脚本,我发现它可以工作。但是,当我使用lxml 库执行相同操作时,它不再起作用。我怎样才能让我的后一个脚本工作?谢谢。
这是内容:
html_content="""
<tr>
<td width="25%" valign="top" bgcolor="lightgrey" nowrap="">
<font face="Arial" size="-1" color="224119">
<b>Owner Address </b>
</font>
</td>
<td width="75%" valign="top" nowrap="">
<font face="Arial" size="-1" color="black">
1698 EIDER DOWN DR<br>SUMMERVILLE SC 29483
</font>
</td>
</tr>
"""
使用 bs4:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_content,"lxml")
item = soup.select("td")[0].find_next_sibling().text
print(item)
结果:
1698 EIDER DOWN DRSUMMERVILLE SC 29483
下面的脚本可以找到地址字符串:
from lxml.html import fromstring
root = fromstring(html_content)
item = root.cssselect("td b:contains('Address')")[0].text
print(item)
结果:
Owner Address
在查找下一个兄弟时不起作用(应用“+”号查找下一个兄弟:
from lxml.html import fromstring
root = fromstring(html_content)
item = root.cssselect("td b:contains('Owner Address')+td")[0].text
print(item)
结果:
Traceback (most recent call last):
File "C:\Users\ar\AppData\Local\Programs\Python\Python35-32\new_line_one.py", line 28, in <module>
item = root.cssselect("td b:contains('Owner Address')+td")[0].text
IndexError: list index out of range
我怎样才能找到下一个兄弟姐妹?顺便说一句,我只关注css选择器而不是xpath。谢谢。
【问题讨论】:
标签: python python-3.x web-scraping css-selectors lxml