python - 如何使用 lxml.etree python 中的类名解析 html

标签 python python-2.7 beautifulsoup lxml

req = requests.get(url)
tree = etree.HTML(req.text)

现在而不是使用 xpath tree.xpath(...) 我想知道我们是否可以像在 beautifulSoup 中那样通过 id 的类名进行搜索 soup.find('div',attrs={'class':'myclass'}) 我正在lxml中寻找类似的东西。

最佳答案

bs4 中执行此操作的更简洁方法是使用 css 选择器:

soup.select('div.myclass') #  == soup.find_all('div',attrs={'class':'myclass'})

lxml 提供 cssselect 作为模块(实际上是 compiles XPath expressions )和 Element 对象上的便捷方法。

import lxml.html

tree = lxml.html.fromstring(req.text)
for div in tree.cssselect('div.myclass'):
    #stuff

或者您可以选择预编译表达式并将其应用到您的Element:

from lxml.cssselect import CSSSelector
selector = CSSSelector('div.myclass')

selection = selector(tree)

关于python - 如何使用 lxml.etree python 中的类名解析 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23615355/

相关文章:

python - 使用 Beautiful Soup 从非类部分获取数据

python - 循环顺序问题

python - BeautifulSoup 不能使用 if is None then continue 语句来避免 'NoneType' object is not subscriptable Type Error

python - 如何在 python 调试器 PuDB 中重复命令行上的最后一个命令

python - Tkinter根窗口类继承,在__init__中添加widgets

python - 通过 python 禁用谷歌驱动器文件的下载选项

python - docx 在 python 中列出

python - 如何将 BeautifulSoup 标签转换为 JSON?

python - 如何使用元组列表中的元组中的值作为函数的参数?

python - Django 外键 : get related model?