我用 python 结合 lxml libary 编写了一个脚本,用于从一大块 html 元素
中解析一些 price
(本例中为 80 和 100)。我使用 xpaths 来完成这项工作。当我使用 .fromstring()
时,我在下面的抓取工具中使用的两个 xpath
都可以完美地工作。但是,当我选择使用从 lxml.etree
导入的 HTML
时,xpath containsig contains()
表达式会失败。事实证明,当我在抓取器中使用多个类
名称时,它可以工作,但是当从复合类名称
中选择一个单个类名称
时,它就可以了抛出错误。
如何在不使用复合类名
的情况下处理这种情况;而是使用遵循.contains()
模式的单个类名
或东西?
这是我的尝试:
from lxml.etree import HTML
elements =\
"""
<li class="ProductPrice">
<span class="Regular Price">80.00</span>
</li>
<li class="ProductPrice">
<span class="Regular Price">100.00</span>
</li>
"""
root = HTML(elements)
for item in root.findall(".//*[@class='ProductPrice']"):
# regular = item.find('.//span[@class="Regular Price"]').text
regular = item.find('.//span[contains(@class,"Regular")]').text
print(regular)
顺便说一句,上面脚本中使用的注释掉的xpath
工作正常。但无法使用 .contains()
表达式,它会引发以下错误:
Traceback (most recent call last):
File "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\SO.py", line 15, in <module>
regular = item.find('.//span[contains(@class,"Regular")]').text
File "src\lxml\etree.pyx", line 1526, in lxml.etree._Element.find
File "src\lxml\_elementpath.py", line 311, in lxml._elementpath.find
File "src\lxml\_elementpath.py", line 300, in lxml._elementpath.iterfind
File "src\lxml\_elementpath.py", line 283, in lxml._elementpath._build_path_iterator
File "src\lxml\_elementpath.py", line 229, in lxml._elementpath.prepare_predicate
SyntaxError: invalid predicate
最后一件事:我不想使用复合类名
,因为很少有网站动态生成它们。谢谢。
最佳答案
.find()
仅支持基本的 xpath。
尝试.xpath()
。
示例(未经测试)...
regular = item.xpath('.//span[contains(@class,"Regular")]')[0].text
参见http://lxml.de/xpathxslt.html了解更多详情。
关于python - 即使使用正确的 xpath,Scraper 也会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50649171/