xpath解析:最常用且比较便捷的一种解析方式。通用性
- xpath解析原理:
- –1.实例化一个etree对象,且将且需要将解析的页面的数据加载到该对象中。
- –2.调用etree对象中的xpath方法结合着xpath表达式实现标签的定位和内容的捕获。
- 环境的安装
- 1.cmd方法
pip install lxml - 直接在pycharm中直接安装(更简单)
- 1.cmd方法
- 如何实例化一个对象
- –1.将本地文档中的源代码加载带etree对象中:
etree.parse(‘fileName’) - –2.可以从互联网上获取的源代码加载到该对象中
etree.HTML(‘fileName’) - – 3.xpath表达式
- –1.将本地文档中的源代码加载带etree对象中:
- xpath表达式(重点)
- — /:表示的是从根节点开始定位。表示是一个层级。
r = tree.xpath(’/html/div/p’) - — //:表示的是多个层级。可以表示从任意位置开始定位。
#r = tree.xpath(’//p’)
#r = tree.xpath(’/html//p’) - —属性定位:
//div[@class=‘song’] ---->tag[@attrName=“attrValue”] - — 索引定位:
//div[@class=“song”]/p[3] 索引是从1开始的。 - — 取文本:
- /text() 获取的是标签中直系的文本内容
- //text() 标签中非直系的文本内容(所有的文本内容) - — 取属性:
/@attrName ==>img/src
r = tree.xpath(’//div[@class=“tang”]//li[3]/a/@href’)[0]
- — /:表示的是从根节点开始定位。表示是一个层级。
例子:
from lxml import etree
if __name__ == "__main__":
tree = etree.parse('test.html')
#r=tree.xpath('/html/head/)
#r = tree.xpath('/html//p')
#r = tree.xpath('//p')
r = tree.xpath('//div[@class="tang"]//li[3]/a/@href')[0]
print(r)
实例1:58同城
import requests
from lxml import etree
if __name__ == "__main__":
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'
}
url='https://zz.58.com/ershoufang/?PGTID=0d200001-0015-6095-00a5-32e38bd5575e&ClickID=1'
response = requests.get(url=url,headers=headers).text
li_list = etree.HTML(response)
list_all=li_list.xpath('//div[@class="property-content"]')
fp = open('58.txt', 'w', encoding='utf-8')
for list in list_all:
title = list.xpath('./div[@class="property-content-detail"]//h3/text()')[0]
money= list.xpath('./div[@class="property-price"]/p/span[@class="property-price-total-num"]/text()')[0]
print(title,money+"万")
fp.write(title)
fp.write(money+"万"+"/n")
案例2:全国城市名字
import requests
from lxml import etree
if __name__ == "__main__":
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'
}
url='https://www.aqistudy.cn/historydata/'
City_list = requests.get(url=url,headers=headers).text
tree = etree.HTML(City_list)
city_list = tree.xpath('//div[@class="bottom"]/ul/li/a | //div[@class="bottom"]/ul/div[2]/li/a')
ALL_city=[]
for a in city_list:
city_N = a.xpath('./text()')[0]
ALL_city.append(city_N)
print(ALL_city,len(ALL_city))
其中’//div[@class=“bottom”]/ul/li/a | //div[@class=“bottom”]/ul/div[2]/li/a’重点,两者皆可以。