淘宝商品比价定向爬虫【MOOC实例微优化】

MOOC北京理工大学嵩天老师的公开课上有一个淘宝商品比价定向爬虫的实例,这个小的定向爬虫代码可以对淘宝网上一个搜索关键词进行检索,可以获取检索页面的某件产品的相关信息,比如价格、名称、销量等等。通过这些爬取获得的数据,我们可以简单的了解某件产品的销量如何,也可以为我们筛选产品提供一些小的支持。源代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import requests
import re
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def parsePage(ilt, html):
try:
plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)
for i in range(len(plt)):
price = eval(plt[i].split(':')[1])
title = eval(tlt[i].split(':')[1])
ilt.append([price , title])
except:
print("")
def printGoodsList(ilt):
tplt = "{:4}\t{:8}\t{:16}"
print(tplt.format("序号", "价格", "商品名称"))
count = 0
for g in ilt:
count = count + 1
print(tplt.format(count, g[0], g[1]))
def main():
goods = '书包'
depth = 3
start_url = 'https://s.taobao.com/search?q=' + goods
infoList = []
for i in range(depth):
try:
url = start_url + '&s=' + str(44*i)
html = getHTMLText(url)
parsePage(infoList, html)
except:
continue
printGoodsList(infoList)
main()

由于淘宝现在对搜索进行了登录限制,所以目前这个实例已经没有办法对搜索关键词进行数据爬取了。现在必须使用header模拟浏览器和键入cookie或者使用更高级的技术才可以正常爬取。这里我使用了cookies去进行一些简单的爬取,并且对嵩老师的代码进行了一点简单的优化。主要增加了销量的数据,还有发货地的数据,并且根据销量重新进行排序,并且最后生成一个csv文件储存在本地。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# -*- coding: utf-8 -*-
"""
Created on Sun May 17 07:48:17 2020
@author: Luzhi based on 嵩天
"""
import requests
import re
import pandas as pd
def getHTMLText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.text
except:
return ""
def parsePage(ilt,html):
try:
plt=re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
slt=re.findall(r'\"view_sales\"\:\".*?\"',html)
llt=re.findall(r'\"item_loc\"\:\".*?\"',html)
tlt=re.findall(r'\"raw_title\"\:\".*?\"',html)
for i in range(len(plt)):
price=eval(plt[i].split(":")[1])
sales=eval(slt[i].split(":")[1])
location=eval(llt[i].split(":")[1])
title=eval(tlt[i].split(":")[1])
ilt.append([price,sales,location,title])
except:
print("")
def printGoodsList(ilt):
tplt = "{:4}\t{:4}\t{:4}\t{:4}\t{:8}"
print(tplt.format("序号","价格","销量","发货地","商品名称"))
count=0
for g in ilt:
count=count+1
print(tplt.format(count,g[0],g[1],g[2],g[3]))
print("")
def main():
goods="狗粮"
depth=2
start_url="https://s.taobao.com/search?q="+goods
infoList=[]
for i in range(depth):
try:
url=start_url +"&s="+str(44*i)
headers={
"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36", #浏览器信息
"cookie": "" #可以通过F12进入浏览器开发者模式获取
}
html=requests.get(url,headers=headers)
print(html.text)
parsePage(infoList,html.text)
except:
continue
#printGoodsList(infoList)
df = pd.DataFrame(infoList, columns = ["价格","销量","发货地","商品名称"])
df['销量'] = df['销量'].str.replace('人付款','') #把'人付款'中文字符替换为空
cleaner = df['销量'].str.contains('万') #把含有'万‘字的销量数据提出
trimmer = df['销量'].str.replace(r'[\u4e00-\u9fa5]\+|\+','') #替换掉销量带'万+'和'+'的数据
df.loc[cleaner, '销量'] = trimmer.astype('float') * 10000 #把去除'万+'数据乘以10000
cleaner2 = df['销量'].apply(str).str.contains('\+')
trimmer2 = df['销量'].apply(str).str.rstrip('\+')
df.loc[cleaner2, '销量']=trimmer2
df['销量'] = df['销量'].astype('float')
df.sort_values(by='销量', ascending=False, inplace=True)
df2 = df.join(df['发货地'].str.split(' ', expand=True)) #把发货地分割成省/市
df2.columns = ['价格','销量','发货地','商品名称', '发货省','发货市']
df2.drop(['发货地'], axis=1, inplace=True)
order = ['价格','销量', '发货省','发货市','商品名称'] #重新把列排序
df2 = df2[order]
df2['发货市'] = df2['发货市'].apply(str).str.replace('None', '')
df.sort_values(by='销量', ascending=False, inplace=True) #按销量由大到小排序
print(df2)
df2.to_csv('C:\\Users\\Admin\\Desktop\\list.csv',index=False,header=True, encoding='utf_8_sig') #储存csv文件到本地
main()

你将会大致得到如下所示的一个csv文件:



0%