【问题标题】:how to parse html by using class name in lxml.etree python如何在 lxml.etree python 中使用类名解析 html
【发布时间】:2014-06-30 04:31:58
【问题描述】:
req = requests.get(url)
tree = etree.HTML(req.text)
现在不使用 xpath tree.xpath(...) 我想知道我们是否可以像在 beautifulSoup 中那样通过 id 的类名进行搜索
soup.find('div',attrs={'class':'myclass'})我正在lxml中寻找类似的东西。
【问题讨论】:
标签:
python
python-2.7
beautifulsoup
lxml
【解决方案1】:
在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)
【解决方案2】:
您说您不想使用 xpath,但没有解释原因。如果目标是搜索具有给定类的标签,您可以使用 xpath 轻松完成。
例如,要查找类为“foo”的 div,您可以执行以下操作:
tree.find("//div[@class='foo']")