将淘宝爬取的数据写入Excel表格

编程入门 行业动态 更新时间:2024-10-27 18:25:26

将<a href=https://www.elefans.com/category/jswz/34/1768348.html style=淘宝爬取的数据写入Excel表格"/>

将淘宝爬取的数据写入Excel表格

我们上一篇文章已经获取到淘宝的数据写入了.json文件。现在我们就可以写入Excel表格。

 运行结果是这样子的。

from selenium.webdriver import Chrome
import time
from lxml import etree
import json
import xlwt
#导包
if __name__ == '__main__':chrome_obj = Chrome()#因为是个类,所以要创建一个对象。chrome_obj.get('=mm_26632258_3504122_32538762&keyword=%E5%A5%B3%E8%A3%85&clk1=ab1fdcf6365ee8bc6248263f22f49a33&upsId=ab1fdcf6365ee8bc6248263f22f49a33')  # 往浏览器的网页地址栏填入淘宝网址#先定位到搜索框input_obj = chrome_obj.find_element_by_xpath('//*[@id="J_search_key"]').clear()# 输入搜索框数据input_obj = chrome_obj.find_element_by_xpath('//*[@id="J_search_key"]').send_keys('男装')#定位到点击搜索按钮click_obj = chrome_obj.find_element_by_xpath('//*[@id="J_searchForm"]/input')# 触发点击click_obj.click()# 页面等待,等待数据加载完毕time.sleep(2)# 获取源码数据html_data = chrome_obj.page_source# 数据的提取:html_obj = etree.HTML(html_data)# 商品名name_list = html_obj.xpath('//div/span[@class="title-text"]/text()')print(name_list)#商品销量sell_info = html_obj.xpath('//div/div[@class="sell-info"]/text()')print(sell_info)#商品价格//div/span[@class="coupon-price-afterCoupon"]/text()jiage = html_obj.xpath('//div/span[@class="coupon-price-afterCoupon"]/text()')print(jiage)book = xlwt.Workbook(encoding='utf-8', style_compression=0)#表格明如sheetsheet = book.add_sheet('淘宝', cell_overwrite_ok=True)#写出第一行的列col = ('商品名称', '价格', '销量')for i in range(0, 3):sheet.write(0, i, col[i])#将数据合并为一个列表,一个列表里面嵌套多个列表,我们不需要知道有多少,直接len(name_list)就可以知道有多少个dict_ = []for i in range(len(name_list)):dict_1 = [name_list[i], sell_info[i], jiage[i]]print(dict_1)dict_.append(dict_1)print(dict_)
#将数据以一个列表写入Excel表格for i in range(0, 60):data = dict_[i]for j in range(0, 3):sheet.write(i + 1, j, data[j])#这一步我们要在D:/python项目/ 这个目录下先新建一个叫taobao.xls的文件,不然会报错savepath = 'D:/python项目/taobao.xls'book.save(savepath)#打开文件后要关闭才能运行,不然会报权限不够的错误。#关闭浏览器chrome_obj.quit()

更多推荐

将淘宝爬取的数据写入Excel表格

本文发布于:2023-06-27 19:31:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/915951.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:淘宝   表格   数据   Excel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!