1、xpath
1.1、xpath环境
浏览器下载xpath插件
chrome插件下载
提取码:5iex
python安装lxml库
pip install lxml -i https://pypi.douban.com/simple
1.2、xpath使用
1.etree.parse() 解析本地文件
html_tree = etree.parse(‘xxx.html’)
2.etree.HTML() 服务器响应文件
html_tree = etree.HTML(response.read().decode(‘utf-8’))
3.html_tree.xpath(xpath路径)
4.路径获取
鼠标右键查看网页源代码
快捷键 Ctrl + Shift + x 打开xpath工具
在Query框输入路径,在Result中显示定位的值
1.3、xpath基本语法
1.路径查询
//:查询所有子孙节点,不考虑层级关系
/:找直接子节点
2.谓词查询
//div[@id]
//div[@id=“maincontent”]
3.属性查询
//@class
4.模糊查询
//div[contains(@id,“he”)]
//div[start-with(@id,“he”)]
5.内容查询
//div/h1/text()
6.逻辑运算
//div[@id=“head” and @class=“s_down”]
//title | //price
1.4、应用实例:爬取站长素材图片
import urllib.request from lxml import etree def create_request(page): if (page == 1): url = 'https://sc.chinaz.com/tupian/meinvtupian.html' else: url = 'https://sc.chinaz.com/tupian/meinvtupian_' + str(page) + '.html' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36' } request = urllib.request.Request(url=url,headers=headers) return request def get_content(request): response = urllib.request.urlopen(request) content = response.read().decode('utf-8') return content def down_load(content): # 解析网页源码 tree = etree.HTML(content) name_list = tree.xpath('//div[@id="container"]//a/img/@alt') src_list = tree.xpath('//div[@id="container"]//a/img/@src') # 下载图片到本地 for i in range(len(name_list)): name = name_list[i] src = src_list[i] url = 'https:' + src urllib.request.urlretrieve(url=url,filename='./images/'+name+'.jpg') if __name__ == '__main__': start_page = int(input("请输入起始页码:")) end_page = int(input("请输入结束页码:")) for page in range(start_page, end_page + 1): request = create_request(page) content = get_content(request) down_load(content)
2、jsonpath
文章推荐:https://blog.csdn.net/luxideyao/article/details/77802389
3、bs4
无