首页 热点资讯 义务教育 高等教育 出国留学 考研考公

怎么利用爬虫技术抓取淘宝搜索页面的产品信息

发布网友

我来回答

3个回答

懂视网

这次的主要的目的是从淘宝的搜索页面获取商品的信息。其实分析页面找到信息很容易,页面信息的存放都是以静态的方式直接嵌套的页面上的,很容易找到。主要困难是将信息从HTML源码中剥离出来,数据和网页源码结合的很紧密,剥离数据有一定的难度。

然后将获取的信息写入excel表格保存起来,这次只爬取了前面10页的内容。

代码如下:

import requests
import re
from xlwt import Workbook
import xlrd
import time
def key_name( number ):
 #获取页面的内容并返回
 name = '手机'
 URL_1 = "https://s.taobao.com/search?ie=utf8&initiative_id=staobaoz_20170905&stats_click=search_radio_all%3A1&js=1&imgfile=&q="
 URL_2 = "&suggest=0_1&_input_charset=utf-8&wq=u&suggest_query=u&source=suggest&p4ppushleft=5%2C48&s="
 URL = ( URL_1 + name + URL_2 + str(number))
 #print(URL)
 res = requests.get( URL )
 return res.text
def find_date( text):
 #根据整个页面的信息,获取商品的数据所在的HTML源码并放回
 reg = r',"data":{"spus":[({.+?)]}},"header":'
 reg = re.compile(reg)
 info = re.findall(reg, text)
 return info[0]
def manipulation_data( info, N, sheet ):
 #解析获取的HTML源码,获取数据
 Date = eval(info)
 for d in Date:
 T = " ".join([t['tag'] for t in d['tag_info']])
 #print(d['title'] + '	' + d['price'] + '	' + d['importantKey'][0:len(d['importantKey'])-1] + '	' + T)
 
 sheet.write(N,0,d['title'])
 sheet.write(N,1,d['price'])
 sheet.write(N,2,T)
 N = N + 1
 return N
 
 
def main():
 
 book = Workbook()
 sheet = book.add_sheet('淘宝手机数据')
 sheet.write(0,0,'品牌')
 sheet.write(0,1,'价格')
 sheet.write(0,2,'配置')
 book.save('淘宝手机数据.xls')
 #k用于生成链接,每个链接的最后面的数字相差48.
 #N用于记录表格的数据行数,便于写入数据
 k = 0
 N = 1
 for i in range(10+1):
 text = key_name( k + i * 48 )
 info = find_date(text)
 N = manipulation_data( info ,N, sheet )
 
 book.save('淘宝手机数据.xls')
 print('下载第' + str(i) + '页完成')
if __name__ == '__main__':
 main()

更多Python相关技术文章,请访问Python教程栏目进行学习!

热心网友

可以通过requests库re库进行淘宝商品爬虫爬取
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("F")

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 = 2
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()
这段代码在过去是可以爬取淘宝商品信息,但是因为淘宝的反扒技术升级,便不能让你大摇大摆地进出自如了。
此外也可以借助采集实现采集

热心网友

写个脚本定时抓取 制定网页地址,通过正则表达式 匹配过滤想要的数据 整理成自己想要的格式(比如excel)。
PHP 语言的话,可以用 file_get_content、curl。
Linux 可以用 curl wget 等。

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com