爬取中国城市前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">



