cssselector:和xpath是使用比较多的两种数据提取方式。cssselector是css样式选择器实现的!
scrapy爬虫框架:支持xpath/css
pyspider爬虫框架:支持PyQuery,也是经过css样式选择器实现的css
HTML代码示例:html
html = """
哈哈TwoThreeFour
百度一下
第一段
第2段
第3段
第4段
大师傅大师傅!!
第5段
第6段
"""
安装:
pip install cssselector
首先导入:
import cssselect
from lxml.html import etree
将HTML解析成为对象:
#同xpath同样使用etree
html_obj = etree.HTML(html)
开始查找元素:
获取文本内容python
span = html_obj.cssselect('.list > .four')[0]
print(span.text)
获取属性值:框架
span = html_obj.cssselect('.list > .four')[0]
#help(对象):能够显示对对象的全部操做
print(help(span))
# 获取属性:是一个字典
print(span.attrib['class'])
输出结果:four four1 four2 four3
其余的部分参考博客(CSS选择器——cssSelector定位方式详解):点击打开连接scrapy
PyQuery查找元素:点击打开连接
ide
如果觉得《python爬虫获取页面元素的css样式 Python爬虫数据提取方式——cssselector样式选择器...》对你有帮助,请点赞、收藏,并留下你的观点哦!