利用python爬取信息并保存到excel

哈喽 ,大家好!今天小编为大家带来一个非常实用的小技巧 我们如何把爬取的信息保存到excel。
首先我们讲存入excel经常用到的库,xlrd,xlwt,xlwings,openpyxl,xlsxwriter等等有很多,但是我用的是openpyxl这个库去保存的信息到excel。

openpyxl是一个用于读取和编写Excel 2010 xlsx/xlsm/xltx/xltm文件的库。

下载openpyxl
windows +R 打开cmd 输入命令 pip install openpyxl

利用python爬取信息并保存到excel_第1张图片

pip install openpyxl

接下来就是如何创建excel

import openpyxl
 
#打开文件
wb = openpyxl.Workbook()
 
#使用的工作对象创建一张表
sheet1 = wb.active
 
#在sheet1表中写入内容    插入内容
 
sheet1.append['姓名','性别'] #等等  这是在excel第一行插入,可以相当于一个文件的表头
 
#默认创建新的表单 放在最后
sheet2 = wb.create_sheet('title')
 
#修改表名
sheet2.title ='new sheet'
 
#颜色
sheet1.sheet_properties.tabColor= '000000'
 
# 关闭保存工作簿          
wb.save('文件名.xlsx')

比如我爬取的一个婚恋网站-我主良缘

首先我们要解析它的网页地址

因为我们所需要的信息和内容是在list下面 ,而list又在data下面 所以我们可以用一个for循环把它遍历出来,代码如下:


​for item in json['data']['list']:          
        username=item['username']
        gender = item['gender']
        userid=item['userid']
        province=item['province']
        height = item['height']
        city = item['city']
        astro = item['astro']
        birthdayyear = item['birthdayyear']
        salary = item['salary']
        avatar=item['avatar']
        monolog = item['monolog']
        print("ID:"+userid,"姓名:"+username,"性别:"+gender,"省份::"+province,"城市:"+city,"出生年日:"+birthdayyear,"身高:"+height,"工资:"+salary,"照片:"+avatar,"星座:"+astro,"内心独白:"+monolog)


既然我们需要把信息保存到excel中 那么就需要把上面这段代码放在创建excel表的代码当中。

完整代码如下:

#打开文件
wb = openpyxl.Workbook()

#使用的工作对象创建一张表
sheet1 = wb.active

#在sheet1表中写入内容    插入内容

sheet1.append(['ID','姓名','性别','省份','城市','出生年日','身高(cm)','工资','照片','星座','内心独白'])

for page in range(1,10): #获取1到10页的内容
    
    #根据用户输入的数据,获取服务返回的数据
    
    json = get_data(page,startage,endage,gender,startheight,endheight,salary)

    #print(json['data']['list'])
  
    for item in json['data']['list']:
                
              username=item['username']

              gender = item['gender']

              userid=item['userid']

              province=item['province']

              height = item['height']

              city = item['city']

              astro = item['astro']

              birthdayyear = item['birthdayyear']

              salary = item['salary']

              avatar=item['avatar']

              monolog = item['monolog']
        
    
              print("ID:"+userid,"姓名:"+username,"性别:"+gender,"省份::"+province,"城市:"+city,"出生年日:"+birthdayyear,"身高:"+height,"工资:"+salary,"照片:"+avatar,"星座:"+astro,"内心独白:"+monolog)

            
              
              print('开始写入ecxel,请稍等...',end='')

              xx_info = [userid,username,gender,province,city,birthdayyear,height,salary,avatar,astro,monolog]
              
              sheet1.append(xx_info)

              print('写入成功\n')
        # 关闭保存工作簿
        
wb.save('相亲网站数据抓取.xlsx')

好了 今天小编就讲到这里啦

你可能感兴趣的:(python)