xpath解析

  1.环境安装

pip install lxml

2.解析原理

2.1实例化一个etree的对象,且将待解析的页面源码数据加载到该对象中

2.2调用etree对象的xpath方法结合着不同的xpath表达式实现标签的定位和数据提取

3.实例化etree对象

etree.parse('filename'):将本地html文档加载到该对象中

etree.HTML(page_text):网站获取的页面数据加载到该对象

4.标签定位

from lxml import etree

tree = etree.parse('test.html')

最左侧的/:如果xpath表达式最左侧是以/开头啧表示该xpath表达式一定要从跟标签开始定位标签

非最左侧的/:表示一个层级

非最左侧的//:表示多个层级

最左侧的//:xpath表达式可以从任意位置进行标签定位

#都定位meta
tree.xpath('html/head/meta')
tree.xpath('html//meta')
tree.xpath('//meta')

属性定位:tagName[@attrName='value']

#定位class位为song的div下面所有的p标签
tree.xpath('//div[@class='song']/p')

索引定位:tag.[index]:索引是从1开始的

#定位class位为song的div下面第一个的p标签
tree.xpath('//div[@class='song']/p[1]')

模糊匹配

//div.[contains(@class,"ng")]  # 匹配class包含ng

5.取文本

/text:直系文本内容

//text:所有文本内容

#定位class位为song的div下面第一个的p标签下所有文本内容
tree.xpath('//div[@class='song']/p[1]//text()')

6.取属性

/attrName

tree.xpath('//a[@id="geng"/href]')  # 取a标签下id等于geng的href

 局部数据解析

将定位到的页面中的标签作为待解析数据,再次使用xpath表达式解析待解析的数据

在局部数据解析的时候,xpath表达式中要使用./的操作, ./表示的就是当前的局部数据(xpath的调用者)

xpath表达式通用性

在xpath表达式中使用管道符分割的作用,可以表示管道符左右两侧的子xpath表达式同时生效或者一个生效

import requests
from bs4 import BeautifulSoup
from lxml import etree
import os

url = "https://www.aqistudy.cn/historydata/"
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"}

res = requests.get(url=url,headers=headers).text
data = etree.HTML(res)
# #解析出热门城市名称
# hot_city = data.xpath('//div[@class="bottom"]/ul/li/a/text()')
# #解析出全部城市名称
# all_city = data.xpath('//div[@class="bottom"]/ul/div[2]/li/a/text()')

#解析出热门城市名称和全部城市名称
city = data.xpath('//div[@class="bottom"]/ul/li/a/text() | //div[@class="bottom"]/ul/div[2]/li/a/text()')

 

posted @ 2023-05-26 17:59  小青年て  阅读(84)  评论(0)    收藏  举报