我们上一篇文章已经获取到淘宝的数据写入了.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('https://uland.taobao.com/sem/tbsearch?refpid=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)
#表格明如sheet
sheet = 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()