使用xpath解析一个简单的html文件,想获取href属性的值:
html = etree.parse('test.html',etree.HTMLParser())
print(html.xpath('//li/a@href'))
运行后报错:lxml.etree.XPathEvalError: Invalid expression
Traceback (most recent call last):
File "D:/PythonWorkstation/python3_spider/chap04_解析库/test_xpath.py", line 35, in <module>
print(html.xpath('//li/a@href'))
File "src\lxml\lxml.etree.pyx", line 2272, in lxml.etree._ElementTree.xpath (src\lxml\lxml.etree.c:67766)
File "src\lxml\xpath.pxi", line 359, in lxml.etree.XPathDocumentEvaluator.__call__ (src\lxml\lxml.etree.c:171818)
File "src\lxml\xpath.pxi", line 227, in lxml.etree._XPathEvaluatorBase._handle_result (src\lxml\lxml.etree.c:170189)
lxml.etree.XPathEvalError: Invalid expression
原因分析:
获取属性的值的时候,需要给属性加上中括号。
修改后的代码:
html = etree.parse('test.html',etree.HTMLParser())
print(html.xpath('//li/a/@href'))
再次运行:
D:\python3\Anaconda3\python.exe D:/PythonWorkstation/test_xpath.py
['linkl.html', 'link2.html', 'link3.html', 'link4.html']
Process finished with exit code 0
版权声明:本文为lm3758原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。