1.背景
前幾天接了一個爬蟲的單子,上周六已經完成這個單子,也收到了酬勞(數目還不錯,哈哈哈,小喜了一下)。這個項目大概我用了兩天寫完了(空閑時間寫的)。
2.介紹
大概要采集的數據步驟:1)輸入商品名稱;2)搜索供應商;3)爬取所有供應商的里所有商品數據和對應商品的交易數據;
alibaba國際淘寶鏈接:
https://www.alibaba.com/
1.這個爬蟲項目是對alibaba國際淘寶網站采集數據。
2.通過輸入商品,比如:藍牙耳機
tws+bluetooth+earphone
鏈接
https://www.alibaba.com/trade/search?fsb=y&IndexArea=company_en&CatId=&SearchText=tws%2Bbluetooth%2Bearphone&viewtype=&tab=
3.其中某一個商家的所有商品
鏈接
https://bhdchina.en.alibaba.com/productlist.html?spm=a2700.shop_cp.88.30
4.對應的交易數據記錄
鏈接
https://bhdchina.en.alibaba.com/company_profile/transaction_history.html?spm=a2700.shop_cp.13934.2.2c8f3fa0rt2lHo
3.爬取商家信息
為什么要先爬取商家信息,因為商品數據和交易數據都是需要根據商家名稱去爬取,所有先開始爬取商家信息。
導入庫包
import requests
import json
from lxml import etree
import datetime
import xlwt
import os
import time
requests請求頭
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0'
}
先看看要采集哪些字段
紅框中的這些數據都是需要的(years,product_img,product_title,supperherf,Main Products,Country_Region,Total_Revenue,Top3_Markets,Transactions_6months,Response_Rate......)
其中supperherf是從url鏈接里面提取出的商家名稱,后面爬取商品數據和交易數據需要用到
解析網頁標簽
比如名稱對應的網頁標簽div是title ellipsis,在代碼里面通過xpath可以解析到內容(這里都比較簡單所以就介紹原理,小白不懂的可以看之前的文章去進行學習)
請求url數據
url = "https://www.alibaba.com/trade/search?spm=a2700.supplier-normal.16.1.7b4779adaAmpGa&page="+str(page)+"&f1=y&n=38&viewType=L&keyword="+keyword+"&indexArea=company_en"
r = requests.get(url, headers=headers)
r.encoding = 'utf-8'
s = r.text
解析字段內容
items = selector.xpath('//*[@class="f-icon m-item "]')
if(len(items)>1):
for item in items:
try:
years = item.xpath('.//*[@class="s-gold-supplier-year-icon"]/text()')
print("years=" + str(years[0])+"YRS")
for i in item.xpath('.//*[@class="product"]'):
product_img = i.xpath('.//*[@class="img-thumb"]/@data-big')[0]
product_title = i.xpath('.//a/@title')[0]
product_img = str(product_img)
index1 = product_img.index("imgUrl:'")
index2 = product_img.index("title:")
product_img = "https:"+product_img[index1 + 8:index2 - 2]
print("product_img="+str(product_img))
print("product_title=" + str(product_title))
title = item.xpath('.//*[@class="title ellipsis"]/a/text()')
print("title="+str(title[0]))
supperherf = item.xpath('.//*[@class="title ellipsis"]/a/@href')[0]
index1 = supperherf.index("://")
index2 = supperherf.index("en.alibaba")
supperherf = supperherf[index1 + 3:index2 - 1]
print("supperherf=" + str(supperherf))
Main_Products = item.xpath('.//*[@class="value ellipsis ph"]/@title')
Main_Products = "、".join(Main_Products)
print("Main Products=" + str(Main_Products))
CTT = item.xpath('.//*[@class="ellipsis search"]/text()')
Country_Region=CTT[0]
Total_Revenue=CTT[1]
Top3_Markets = CTT[2:]
Top3_Markets = "、".join(Top3_Markets)
print("Country_Region=" + str(Country_Region))
print("Total_Revenue=" + str(Total_Revenue))
print("Top3_Markets=" + str(Top3_Markets))
Transactions_6months= item.xpath('.//*[@class="lab"]/b/text()')
print("Transactions_6months=" + str(Transactions_6months))
num = item.xpath('.//*[@class="num"]/text()')[0]
print("num=" + str(num))
Response_Rate = item.xpath('.//*[@class="record util-clearfix"]/li[2]/div[2]/a/text()')[0]
print("Response_Rate=" + str(Response_Rate))
count =count+1
print("count="+str(count))
print("page=" + str(page))
print("------------------")
解析結果
到這里就采集完商家數據了,下面開始爬取商家商品數據
4.采集商品數據
這里商品數據的內容就少了很多(商品圖片imgurl,名稱title,價格piece,最低價格minorder)。
解析網頁標簽
請求網頁數據
url = "https://" + str(compayname) + ".en.alibaba.com/productlist-" + str(
page) + ".html?spm=a2700.shop_pl.41413.41.140b44809b9ZBY&filterSimilar=true&filter=null&sortType=null"
r = requests.get(url, headers=headers)
r.encoding = 'utf-8'
s = r.text
解析標簽內容
items = selector.xpath('//*[@class="icbu-product-card vertical large product-item"]')
if(len(items)>1):
try:
for item in items:
imgurl = item.xpath(
'.//*[@class="next-row next-row-no-padding next-row-justify-center next-row-align-center img-box"]/img/@src')
title = item.xpath('.//*[@class="product-info"]/div/a/span/text()')
piece = item.xpath('.//*[@class="product-info"]/div[@class="price"]/span/text()')
minorder = item.xpath('.//*[@class="product-info"]/div[@class="moq"]/span/text()')
print("imgurl=" + str("".join(imgurl)))
print("title=" + str(title[0]))
print("piece=" + str("".join(piece)))
print("minorder=" + str(minorder[0]))
print("count="+str(count))
print("-----------------------------------")
count =count+1
爬取結果
5.爬取交易數據
交易數據需要采集的內容字段也很少,只有三個(交易金額Transaction_Value,買家所屬國家Shipping_Destination,交易時間Transaction_Date)
說明
1)這里金額是***.**,客戶要求是小數點后面的去掉,前面有三位就定義為100~999,如果2位就是10~99
Transaction_Value = Transaction_Value.split(".")[0]
t_len = len(Transaction_Value)
t_start ='1'
t_end='9'
for j in range(1,t_len): # 10 -99
t_start =t_start+"0"
t_end = t_end +'9'
2)時間是12/26/2020,但是采集下來的是1607068800,需要轉為2020-12-27 16:00:00
def todate(timeStamp):
#timeStamp = 1607068800
dateArray = datetime.datetime.fromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
return otherStyleTime
解析網頁標簽
請求網頁數據
url="https://"+str(comapyname)+".en.alibaba.com/core/CommonSupplierTransactionHistoryWidget/list.action?dmtrack_pageid=705d8dfe0b14ebf35fe2e8411768e5b42b8bf0e7a7&page="+str(page)+"&size=8&aliMemberEncryptId=IDX1XQIkua5DjeLlKZC11XM1vlbptpTQfKxDA__pNkStGmQpqTMbPXOgDkVD6T7jySw3&_=1608706140145"
r = requests.get(url)
r.encoding='gbk'
s = json.loads(r.text)
items = s['data']['tradeList']['value']['resultList']
解析內容
if(len(items)>1):
for i in items:
Transaction_Value = i['amt']
Transaction_Value = str(Transaction_Value)
Transaction_Value = Transaction_Value.split(".")[0]
t_len = len(Transaction_Value)
t_start ='1'
t_end='9'
for j in range(1,t_len): # 10 -99
t_start =t_start+"0"
t_end = t_end +'9'
print("Transaction_Value=" + str(Transaction_Value))
print("t_start="+t_start)
print("t_end="+(t_end))
Shipping_Destination = i['countryFullName']
print("Shipping_Destination="+str(Shipping_Destination))
Transaction_Date = i['tradeDate']
Transaction_Date = int(str(Transaction_Date)[:-3])
Transaction_Date = todate(Transaction_Date)
print("Transaction_Date="+str(Transaction_Date))
爬取結果
到這里數據采集的工作已經基本完成了。
6.保存到csv
采集到數據后,需要保存帶csv里
引入csv庫
import xlwt
python寫入csv
# 創建一個workbook 設置編碼
workbook = xlwt.Workbook(encoding = 'utf-8')
worksheet = workbook.add_sheet('sheet1')
worksheet.write(0, 0, label="李運辰")
workbook.save("lyc/lyc_"+str("李運辰") + '.xls')
不懂python寫入csv的,可以參考這篇文章
一篇文章帶你使用 Python搞定對 Excel 表的讀寫和處理(xlsx文件的處理)
商家數據保存到csv
excel表格標題
# 創建一個worksheet
worksheet = workbook.add_sheet('sheet1')
# 參數對應 行, 列, 值
worksheet.write(0, 0, label='years')
worksheet.write(0, 1, label='product_imgs')
worksheet.write(0, 2, label='product_titles')
worksheet.write(0, 3, label='title')
worksheet.write(0, 4, label='supperherf')
worksheet.write(0, 5, label='Main Products')
worksheet.write(0, 6, label='Country_Region')
worksheet.write(0, 7, label='Total_Revenue')
worksheet.write(0, 8, label='Top3_Markets')
worksheet.write(0, 9, label='Transactions_6months')
worksheet.write(0, 10, label='num')
worksheet.write(0, 11, label='Response_Rate')
寫入數據
worksheet.write(count, 0, label=str(years[0]) + "YRS")
worksheet.write(count, 1, label=str(" , ".join(product_imgs)))
worksheet.write(count, 2, label=str(" , ".join(product_titles)))
worksheet.write(count, 3, label=str(title[0]))
worksheet.write(count, 4, label=str(supperherf))
worksheet.write(count, 5, label=str(Main_Products))
worksheet.write(count, 6, label=str(Country_Region))
worksheet.write(count, 7, label=str(Total_Revenue))
worksheet.write(count, 8, label=str(Top3_Markets))
worksheet.write(count, 9, label=str(Transactions_6months[0]))
worksheet.write(count, 10, label=str(num))
worksheet.write(count, 11, label=str(Response_Rate))
供應商數據
商品數據
交易數據
7.結尾
為了讓客戶方便使用,還寫了一個命令行的操作界面
if __name__ == '__main__':
menu()
me = int(input("請輸入:"))
f = 1
while(f):
if me == 1:
print("開始爬取商品數據")
get_product()
elif me == 2:
ke = input("請輸入商品名稱:")
print("開始爬取商家數據,關鍵字:"+str(ke))
supper(ke)
elif me == 3:
print("開始爬取交易數據")
get_trade()
else:
f=0
break
tkinter界面
但是為了方便其他機器上可以使用,我通過python寫了界面
界面源碼
import tkinter as tk
master = tk.Tk()
# 窗口命名
master.title("數據采集v1.0 --李運辰")
# 窗口width不可變,height可變
master.resizable(width=False, height=True)
tk.Label(master, text="商品名稱:").grid(row=0)
# tk.Label(master, text="作者:").grid(row=1)
e1 = tk.Entry(master)
# e2 = tk.Entry(master)
e1.grid(row=0, column=1,columnspan=4, padx=10, pady=5)
w = tk.Label(master, text=str(0)
tk.Button(master, text="終止爬取", width=8, command=isstart).grid(row=3, column=0, sticky="w", padx=1, pady=5)
tk.Button(master, text="商家爬取", width=8, command=supper).grid(row=3, column=1, sticky="e", padx=2, pady=2)
tk.Button(master, text="商品爬取", width=8, command=product).grid(row=3, column=2, sticky="e", padx=3, pady=5)
tk.Button(master, text="交易數據爬取", width=10, command=get_trade).grid(row=3, column=3, sticky="e", padx=4, pady=5)
w.grid(row=4, column=0, columnspan=4, sticky="nesw", padx=0, pady=5)
master.mainloop()
總結
1、以上就是本次的接單的項目過程和工作,本文也是記錄一下這個過程,等以后再看的時候可能是一種享受的感覺,同時也分享給你們,給小白可以學習。
2.大家如果有什么問題的可以在下方進行留言,相互學習。
------------------- End -------------------
Scrapy爬蟲:鏈家全國各省城市房屋數據批量爬取,別再為房屋發愁!
歡迎大家點贊,留言,轉發,轉載,感謝大家的相伴與支持
想加入Python學習群請在后台回復【入群】
萬水千山總是情,點個【在看】行不行
【加群獲取學習資料QQ群:901381280】
【各種爬蟲源碼獲取方式】
識別文末二維碼,回復:爬蟲源碼
歡迎關注公眾號:Python爬蟲數據分析挖掘,方便及時閱讀最新文章
回復【開源源碼】免費獲取更多開源項目源碼