前段时间老师让我爬取淘宝的商品列表以及其商品详情数据,期间遇到了很多问题。最困难的就是淘宝的价格数据是以Ajax异步加载的,这些数据暂时还没有能力获取到。
下面介绍一下基本思路。
首先,通过抓取商品列表的商品ID获取商品的身份标识,然后根据商品ID跳转到具体的商品列表,对其他属性进行抓取。
观察两条商品列表的URL:
https://s.taobao.com/search?q=帽子&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.50862.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170806&bcoffset=7&ntoffset=7&p4ppushleft=1%2C48&s=0
https://s.taobao.com/search?q=帽子&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.50862.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170806&bcoffset=4&ntoffset=4&p4ppushleft=1%2C48&s=44
https://s.taobao.com/search?q=帽子&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.50862.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170806&bcoffset=4&ntoffset=4&p4ppushleft=1%2C48&s=88
这是前三个页面的URL,可以发现,除了"q="和"s="后面的数据不一样,其他的都是一样的,因此,可以把URL简化为:
https://s.taobao.com/search?q=keyword&s=pagenum
其中,q代表搜索的关键词,s代表商品列表的页数,0代表第一页,44代表第二页,88代表第三页……
先以此URL抓取商品的ID等信息。
代码如下。
import re
import requests
from pandas import *
from collections import OrderedDict
def getDetails(startpage,endpage):
#如果需要爬取具体的商品详情,页数过多可能会出现异常,此函数可以用来控制一次爬取的页数
url_head='https://s.taobao.com/search?q=帽子&s='
#这是淘宝搜索列表的url前面的相同部分,q=''代表搜索的关键词,s=''代表第几页,s=0为第1页s=44为第二页,以此类推
url_list=[url_head+str(i*44) for i in range(startpage-1,endpage)] #生成需要爬取的商品列表url
#定义存储商品列表数据数据的列表
nid_list=[]
raw_title_list=[]
view_price_list=[]
view_sales_list=[]
item_loc_list=[]
for url in url_list:
resp=requests.get(url)
print(resp.ur