不,BeautifulSoup 本身不支持 XPath 表达式。
另一个库lxml确实支持 XPath 1.0 。它有一个BeautifulSoup 兼容模式,它会尝试像 Soup 那样解析损坏的 HTML。但是,默认的 lxml HTML 解析器在解析损坏的 HTML 方面同样出色,而且我相信速度更快。
将文档解析为 lxml 树后,您可以使用该.xpath()
方法搜索元素。
try:
# Python 2
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen
from lxml import etree
url = "http://www.example.com/servlet/av/ResultTemplate=AVResult.html"
response = urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
tree.xpath(xpathselector)
还有一个具有附加功能的专用lxml.html()
模块。
请注意,在上面的示例中,我将response
对象直接传递给lxml
,因为让解析器直接从流中读取比先将响应读取到大字符串中更有效。要对requests
库执行相同操作,您希望在启用透明传输解压缩后stream=True
设置并传入response.raw
对象:
import lxml.html
import requests
url = "http://www.example.com/servlet/av/ResultTemplate=AVResult.html"
response = requests.get(url, stream=True)
response.raw.decode_content = True
tree = lxml.html.parse(response.raw)
您可能感兴趣的是CSS 选择器支持;该类CSSSelector
将 CSS 语句转换为 XPath 表达式,使您的搜索td.empformbody
变得更加容易:
from lxml.cssselect import CSSSelector
td_empformbody = CSSSelector('td.empformbody')
for elem in td_empformbody(tree):
# Do something with these table cells.
来个完整的循环:BeautifulSoup 本身确实有非常完整的CSS 选择器支持:
for cell in soup.select('table#foobar td.empformbody'):
# Do something with these table cells.