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

python爬虫:爬取百度热搜pandas存储excel表格

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

python爬虫:爬取百度热搜pandas存储excel表格

百度热搜链接
本章要点:
pandas存储excel

本章目录
  • pandas的使用
  • 百度热搜代码

pandas的使用

pandas的使用方法
安装pandas库:pin3 install pandas

import pandas #导入pandas库
baidu_data = [] #创建个空列表
 baidu_data.append({
 		#要存储的内容以字典的形式追加到列表里
        'title':value, #'title'列名  value 值
        'url':value
    })
# print(baidu_data)
baiduexcel = pandas.Dataframe(baidu_data)#利用列表里的字典创建Dataframe (输出为excel表格样式)
baiduexcel.to_excel('百度热搜.xlsx',index=False)  #index=False 去除excel表格的第一列索引
百度热搜代码

百度热搜代码:

import requests,pandas
from lxml import html
url = 'https://top.baidu.com/board?tab=realtime' #目标网页
res = requests.get(url).text
dom = html.etree.HTML(res)  #解析成能被xpath识别的对象
datas = dom.xpath("//div[@style='margin-bottom:20px']/div/div[2]/a")#获取标题的公共部分(标题+url)
# print(datas)
baidu_data = []
for i in datas:
    # print(i)
    title = i.xpath("div[@class='c-single-text-ellipsis']/text()")[0].strip()#标题
    url = i.xpath("@href")[0]#链接
    # print(title,url)
    baidu_data.append({
        'title':title,
        'url':url
    })
# print(baidu_data)
baiduexcel = pandas.Dataframe(baidu_data) #利用列表里的字典创建Dataframe (输出为excel表格样式)
# print(baiduexcel)
baiduexcel.to_excel('百度热搜.xlsx',index=False)  #index=False 去除excel表格的第一列索引

效果图:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/581159.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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