【问题标题】:How do I select an element with the exact class using cssselect in lxml?如何在 lxml 中使用 cssselect 选择具有确切类的元素?
【发布时间】:2014-04-21 18:20:59
【问题描述】:
我正在使用 lxml html 抓取网页,但遇到了问题。
例如,当我选择 HTML 时:
html.cssselect('a.asig')
我必须获取带有 class="asig" 的元素,但选择还会打印其 id 中包含“asig”的元素,例如:
<a class="asig drcha" ...>
我能做些什么来只获取带有“asig”的元素而不是包含 asig 的元素?
谢谢!
【问题讨论】:
标签:
python
web-scraping
lxml
【解决方案1】:
使用html.xpath 并进行相应调整,或者在声明要定位的类时非常隐含。请参阅以下代码。
from lxml import html
sample = '<?xml version="1.0" encoding="UTF-8"?><root><a class="asig">I am the correct one.</a><a class="asig drcha">I am the wrong one.</a></root>'
tree = html.fromstring(sample)
print tree.xpath("//a[@class='asig']/text()")[0]
print tree.cssselect("a[class='asig']")[0].text
结果如下:
I am the correct one.
I am the correct one.
[Finished in 0.2s]
注意cssselect 在最后一行中是如何使用的。希望这会有所帮助。