报错
Traceback (most recent call last):
File "F:\python3.7.0\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "G:\Projects\pycharmeProject-C21\PyCharm Community Edition 213.5605.23\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
pydev_imports.execfile(filename, global_vars, local_vars)
File "G:\Projects\pycharmeProject-C21\PyCharm Community Edition 213.5605.23\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "G:/Projects/pycharmeProject-C21-3-1/Scrapy/python爬虫_第5章/Chapter_5_xpath_special.py", line 21, in <module>
content = selector.xpath('//div[start-with(@id,"test")]/text()')
File "src\lxml\etree.pyx", line 1597, in lxml.etree._Element.xpath
File "src\lxml\xpath.pxi", line 305, in lxml.etree.XPathElementEvaluator.__call__
File "src\lxml\xpath.pxi", line 225, in lxml.etree._XPathEvaluatorBase._handle_result
lxml.etree.XPathEvalError: Unregistered function
在写xpath解析html的时候报了如上错误,源码如下
源码
```python
import lxml.html
html1 = '''
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="test-1-k">需要的内容1</div>
<div id="test-2-k">需要的内容2</div>
<div id="testfault-k">需要的内容3</div>
<div id="uselessk">这是我不需要的内容</div>
</body>
</html>
'''
selector = lxml.html.fromstring(html1)
content = selector.xpath('//div[start-with(@id,"test")]/text()')
for each in content:
print(each)
分析
这里我是想要获取 div 的id含test的文本内容,于是写了//div[start-with(@id,"test")]/text() 的xpath语句,运行时报了上面的错误,找了半天,没有发现,网上找了一堆也都没有。后来发现他的匹配规则中的方法与大部分编程的字符串方法类似,再仔细一看 start-with 漏掉了s ,加上去就行了。
|