栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【无标题】

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【无标题】

简单爬虫Xpath

爬取中国城市前100名,排行榜
目标网址:https://baike.so.com/doc/24368318-25185095.html

1. 导入库

##导入pandas numpy 和 lxml requests
import pandas as pd ,numpy as np 
import lxml.etree as tree
import requests

2. 构造请求头,然后去get

url = r"https://baike.so.com/doc/24368318-25185095.html"
header={
        'user-agent': 'Mozilla/5.0',
       'accept-language': 'zh-CN,zh;q=0.9',
        'referer': 'https://www.wunderground.com/',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': 'Windows',
        'sec-fetch-dest': 'image',
       }
response = requests.get(url,headers=header)
text = response.text
print(response)


请求成功

3. 查找所需信息

html = tree.HTML(text)
res = html.xpath(r'//div[@]/table/tbody/tr//p/text()')
"""
//div[@]/table/tbody/tr//p 为所需信息位置
/text()查看挑选信息
"""


信息筛选没有问题

4. 保存信息

data = np.array(res).reshape(101,3)
df = pd.Dataframe(data[1:,:],columns = data[0],) 
df.to_excel("./城市排名.xlsx",index =False)

结果如下:

5.xpath用法总结

 //div[@class="h2_content"]/table/tbody/tr//p
 意思是查找:属性为class="h2_content"的div的子标签table的子标签的tbody的子标签tr的子孙标签p
 
 //p 	查找div标签下的内容 xpath(r'//p')
 /tag	查找tag子标签下的内容 xpath(r'/tag')
 //div[@class="h2_content"]] 	查找具有class="h2_content"属性子标签下的内容 xpath(r'//tag[@https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/markdown_views-d7a94ec6ab.css" rel="stylesheet">
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/618800.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号