报错
Traceback (most recent call last):
File "F:python3.7.0libcode.py", line 90, in runcode
exec(code, self.locals)
File "", line 1, in
File "G:ProjectspycharmeProject-C21PyCharm Community Edition 213.5605.23pluginspython-cehelperspydev_pydev_bundlepydev_umd.py", line 198, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "G:ProjectspycharmeProject-C21PyCharm Community Edition 213.5605.23pluginspython-cehelperspydev_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
content = selector.xpath('//div[start-with(@id,"test")]/text()')
File "srclxmletree.pyx", line 1597, in lxml.etree._Element.xpath
File "srclxmlxpath.pxi", line 305, in lxml.etree.XPathElementevaluator.__call__
File "srclxmlxpath.pxi", line 225, in lxml.etree._XPathevaluatorbase._handle_result
lxml.etree.XPathevalError: Unregistered function
在写xpath解析html的时候报了如上错误,源码如下
源码
```python
import lxml.html
html1 = '''
需要的内容1
需要的内容2
需要的内容3
这是我不需要的内容
'''
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,加上去就行了。



