Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 即使使用了正确的xpath,Scraper也会抛出错误_Python_Python 3.x_Xpath_Web Scraping_Lxml - Fatal编程技术网

Python 即使使用了正确的xpath,Scraper也会抛出错误

Python 即使使用了正确的xpath,Scraper也会抛出错误,python,python-3.x,xpath,web-scraping,lxml,Python,Python 3.x,Xpath,Web Scraping,Lxml,我已经用python结合lxml库编写了一个脚本,从html元素块中解析一些price(本例中为80和100)。我使用了xpath来完成这项工作。当我开始使用.fromstring()时,我在我下面的刮刀中使用的XPath和都是无效的。但是,当我选择使用从lxml.etree导入的HTML时,xpath containigcontains()表达式失败。结果表明,当我在scraper中使用多个类名称时,它可以工作,但当从复合类名中选择一个单个类名时,它会抛出一个错误 如果不使用复合类名,如何处理

我已经用python结合lxml库编写了一个脚本,从
html元素块中解析一些
price
(本例中为80和100)。我使用了
xpath
来完成这项工作。当我开始使用
.fromstring()
时,我在我下面的刮刀中使用的
XPath和
都是无效的。但是,当我选择使用从
lxml.etree
导入的
HTML
时,xpath containig
contains()
表达式失败。结果表明,当我在scraper中使用多个
名称时,它可以工作,但当从
复合类名
中选择一个
单个类名
时,它会抛出一个错误

如果不使用
复合类名
,如何处理这种情况;而是在
.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)
最后一件事:我不希望使用
复合类名
,因为很少有网站动态生成它们。谢谢。

.find()
仅支持基本xpath

请尝试
.xpath()

示例(未经测试)


有关详细信息,请参阅。

.find()
仅支持基本xpath。请尝试
.xpath()
。类似于
regular=item.xpath('.//span[contains(@class,“regular”)])[0].text
(未测试)。感谢@Daniel Haley的快速回复。
中使用的
.xpath()
.cssselect()
。fromstring()
.HTML()
的工作原理相同。你应该把它作为回答,这样我才能接受。
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
regular = item.xpath('.//span[contains(@class,"Regular")]')[0].text