爬取数据存储于Excel表

一.利用pandas库直接存储为Excel文件;

     主要技术点:

     1.首先建立列表,存储每一次爬取的内容,为后面的字典存储做准备;

     2.利用字典格式储存数据;

     3. 利用pandas中DataFrame()函数保存字典数据 并利用to_excel()函数储存到exel表格中;

应用举例一:(菜鸟教程python100例url)

from lxml import etree
import requests#导入请求库
import pandas as pd #导入pandas库直接存为exel文件

#菜鸟教程python100例url
recommed_url='https://www.runoob.com/python3/python3-examples.html'
#利用requests的get()方法请求url 并利用decode()方法以'utf-8'解码
res=requests.get(url=recommed_url).content.decode('utf-8')
#利用etree库解析返回的HTML页面
ele=etree.HTML(res)
#利用Xpath()提取详情页的URl
elements=ele.xpath('//*[@id="content"]/ul/li/a/@href')
#利用列表存储所有的URL
url_list=['https://www.runoob.com/python3/'+ele for ele in elements]
url = url_list
#print()输出语句查看解析的详情页url
# print(url_list)
#利用列表存储每一次爬取的内容 为后面的字典存储做准备
title=[]
url = []
body=[]
content = []
#解析详情页的函数
for url in url_list:
    print(url)
    res2 = requests.get(url).content.decode('utf-8')
    ele2=etree.HTML(res2)
    title.append(ele2.xpath('//*[@id="content"]/h1/text()')[0])
    body.append(ele2.xpath('//*[@id="content"]/p[2]/text()')[0])
#利用字典的格式存储数据
data={
    '文章标题':title,
    '文章url':url,
    '题目内容':body,
}
#利用pandas中DataFrame()函数保存字典数据 并利用to_excel()函数储存到exel表格中
df=pd.DataFrame(data)
df.to_excel('cainiao3.xlsx',encoding='utf-8')

函数封装版:

import requests
from lxml import html
etree = html.etree   #解决lxml模块导入etree有误
import pandas as pd
#利用列表存储每一次爬取的内容 为后面的字典存储做准备
title=[]
url = []
body=[]
content = []
# 解析列表页的函数
def get_url_info(recommed_url):
    #利用requests的get()方法请求url 并利用decode()方法以'utf-8'解码
    res=requests.get(recommed_url).content.decode('utf-8')
    #利用etree库解析返回的HTML页面
    ele=etree.HTML(res)
    #利用Xpath()提取详情页的URl
    elements=ele.xpath('//*[@id="content"]/ul/li/a/@href')
    #利用列表存储所有的URL
    url_list=['https://www.runoob.com/python3/'+ele for ele in elements]
    #url_list
    # for url in url_list:
    #     print(url)
    get_url_cainiao(url_list)
    #print()输出语句查看解析的详情页url
    # print(url_list)
# 解析详情页的函数
def get_url_cainiao(url_list):
    for url in url_list:
        print(url)
        res2 = requests.get(url).content.decode('utf-8')
        ele2 = etree.HTML(res2)
        title.append(ele2.xpath('//*[@id="content"]/h1/text()')[0])
        body.append(ele2.xpath('//*[@id="content"]/p[2]/text()')[0])
# 利用字典的格式存储数据
        data = {
            '文章标题': title,
            '文章url': url,
            '题目内容': body,
        }
        # 利用pandas中DataFrame()函数保存字典数据 并利用to_excel()函数储存到exel表格中
        df = pd.DataFrame(data)
        df.to_excel('cainiao0.xlsx', encoding='utf-8')
#主函数程序主入口
if __name__ == '__main__':
    recommed_url = 'https://www.runoob.com/python3/python3-examples.html'
    get_url_info(recommed_url)

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值