一个Python爬虫案例,带你掌握xpath数据解析方法!_python如何获取etree使用xpath的值

etree.HTML(‘page_text’)


### **xpath(‘xpath表达式’)**


* /:表示的是从根节点开始定位。表示一个层级
* //:表示多个层级。可以表示从任意位置开始定位
* 属性定位://div[@class='song'] tag[@attrName='attrValue']
* 索引定位://div[@class='song']/p[3] 索引从1开始的
* 取文本:


	+ /text()获取的是标签中直系的文本内容
	+ //text()标签中非直系的文本内容(所有文本内容)
* 取属性:/@attrName ==>img/src


### **xpath爬取58二手房实例**


爬取网址


https://xa.58.com/ershoufang/完整代码



from lxml import etree
import requests

if name == ‘main’:
    headers = {
        ‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36’
    }
    url = ‘https://xa.58.com/ershoufang/’
    page_text = requests.get(url=url,headers=headers).text
    tree = etree.HTML(page_text)
    div_list = tree.xpath(‘//section[@class=“list”]/div’)
    fp = open(‘./58同城二手房.txt’,‘w’,encoding=‘utf-8’)
    for div in div_list:
        title = div.xpath(‘.//div[@class=“property-content-title”]/h3/text()’)[0]
        print(title)
        fp.write(title+‘\n’+‘\n’)



![图片](https://img-blog.csdnimg.cn/img_convert/d9d5af1d219e7a5ba7b1c500698c9188.png)


### **xpath图片解析下载实例**


爬取网址


https://pic.netbian.com/4kmeinv/完整代码



import requests,os
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/84.0.4147.105 Safari/537.36’
    }
    url = ‘https://pic.netbian.com/4kmeinv/’
    page_text = requests.get(url=url,headers=headers).text
    tree = etree.HTML(page_text)
    li_list = tree.xpath(‘//div[@class=“slist”]/ul/li/a’)
    if not os.path.exists(‘./piclibs’):
        os.mkdir(‘./piclibs’)
    for li in li_list:
        detail_url =‘https://pic.netbian.com’ + li.xpath(‘./img/@src’)[0]
        detail_name = li.xpath(‘./img/@alt’)[0]+‘.jpg’
        detail_name = detail_name.encode(‘iso-8859-1’).decode(‘GBK’)
        detail_path = ‘./piclibs/’ + detail_name
        detail_data = requests.get(url=detail_url, headers=headers).content
        with open(detail_path,‘wb’) as fp:
            fp.write(detail_data)
            print(detail_name,‘seccess!!’)



![图片](https://img-blog.csdnimg.cn/img_convert/133845f1d45a6a558ca5ca51cdbf8d59.png)


### **xpath爬取全国城市名称实例**


爬取网址 


https://www.aqistudy.cn/historydata/完整代码



import requests
from lxml import etree

if name == ‘main’:
    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/87.0.4280.141 Safari/537.36’,
    }
    page_text = requests.get(url=url,headers=headers).content.decode(‘utf-8’)
    tree = etree.HTML(page_text)
    #热门城市   //div[@class=“bottom”]/ul/li
    #全部城市   //div[@class=“bottom”]/ul/div[2]/li
    a_list = tree.xpath(‘//div[@class=“bottom”]/ul/li | //div[@class=“bottom”]/ul/div[2]/li’)
    fp = open(‘./citys.txt’,‘w’,encoding=‘utf-8’)
    i = 0
    for a in a_list:
        city_name = a.xpath(‘.//a/text()’)[0]
        fp.write(city_name+‘\t’)
        i=i+1
        if i == 6:
            i = 0
            fp.write(‘\n’)
    print(‘爬取成功’)


![](https://img-blog.csdnimg.cn/bb7417d15aad419e92ac3d9d2ef4b4cb.png)



### **xpath爬取简历模板实例**


爬取网址


https://sc.chinaz.com/jianli/free.html完整代码



import requests,os
from lxml import etree

if name == ‘main’:
    url = ‘https://sc.chinaz.com/jianli/free.html’
    headers = {
        ‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36’,
    }
    page_text = requests.get(url=url,headers=headers).content.decode(‘utf-8’)
    tree = etree.HTML(page_text)
    a_list = tree.xpath(‘//div[@class=“box col3 ws_block”]/a’)
    if not os.path.exists(‘./简历模板’):
        os.mkdir(‘./简历模板’)
    for a in a_list:
        detail_url = ‘https:’+a.xpath(‘./@href’)[0]
        detail_page_text = requests.get(url=detail_url,headers=headers).content.decode(‘utf-8’)
        detail_tree = etree.HTML(detail_page_text)
        detail_a_list = detail_tree.xpath(‘//div[@class=“clearfix mt20 downlist”]/ul/li[1]/a’)
        for a in detail_a_list:
            download_name = detail_tree.xpath(‘//div[@class=“ppt_tit clearfix”]/h1/text()’)[0]
            download_url = a.xpath(‘./@href’)[0]
            download_data = requests.get(url=download_url,headers=headers).content
            download_path = ‘./简历模板/’+download_name+‘.rar’
            with open(download_path,‘wb’) as fp:

最后

🍅 硬核资料:关注即可领取PPT模板、简历模板、行业经典书籍PDF。
🍅 技术互助:技术群大佬指点迷津,你的问题可能不是问题,求资源在群里喊一声。
🍅 面试题库:由技术群里的小伙伴们共同投稿,热乎的大厂面试真题,持续更新中。
🍅 知识体系:含编程语言、算法、大数据生态圈组件(Mysql、Hive、Spark、Flink)、数据仓库、Python、前端等等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值