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