from lxml import etree
html = ‘‘‘
<li class="tag_1">需要的内容1</li>
<li class="tag_2">需要的内容2</li>
<li class="tag_3">需要的内容3</li>
‘‘‘
selector = etree.HTML(html )
contents = selector.xpath ( ‘//li[@class = "tag_1"]/text()‘)
print(contents)
输出:
D:\Python\venv\Scripts\python.exe D:/Python/venv/test9.py
[‘需要的内容1‘]
Process finished with exit code 0
starts-with()可以获取类似标签的信息。
from lxml import etree
html = ‘‘‘
<li class="tag_1">需要的内容1</li>
<li class="tag_2">需要的内容2</li>
<li class="tag_3">需要的内容3</li>
‘‘‘
selector = etree.HTML(html )
contents = selector.xpath ( ‘//li[starts-with(@class ,"tag")]/text()‘)
for content in contents:
print (content)
输出:
D:\Python\venv\Scripts\python.exe D:/Python/venv/test9.py
需要的内容1
需要的内容2
需要的内容3
Process finished with exit code 0
**
原文:http://blog.51cto.com/12884584/2352679