python - 即使使用正确的 xpath,Scraper 也会抛出错误

标签 python python-3.x xpath web-scraping lxml

我用 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/

相关文章:

python - 循环查找 "bouncy"数字

xml - 使用 XPath 选择 XML 节点时如何忽略命名空间

ruby-on-rails - 使用 Nokogiri 解析简单的 XML

python - 如何索引列表直到遇到特定的数据类型?

python - 查找素数算法的时间复杂度

Python Tkinter Tk 支持检查列表框?

Python 3 导入错误 : No module named 'ConfigParser'

sql-server - 如何从 SQL Server 获取 ROOT 节点名称

Python:带有 if 语句的 numpy where 命令

python - 为什么不在 Python 函数内部的返回函数上使用括号?