欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

爬取淘宝商品

程序员文章站 2023-12-24 12:00:33
...

1:淘宝搜索地址:https://s.taobao.com/search?q=关键词

   例:假如搜索书包,那么搜索地址便为 https://s.taobao.com/search?q=书包

2:翻页处理

爬取淘宝商品

可以发现淘宝每页44个商品,第i页url为 https://s.taobao.com/search?q=关键词&s=(i-1)*44

3:

代码:

import requests
import re
def getHTMLText(url):
	try:
		r = requests.get(url)
		r.raise_for_status()
		r.encoding = r.apparent_encoding
		#print(r.text)
		return r.text;
	except:
		print("getHTMLText Error")
		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 = tlt[i].split(':')[1]
			ilt.append([price, title])
	except:
		print("parsePage Error")
def printGoodsList(ilt):
	tplt = "{:4}\t{:8}\t{:16}"
	print(tplt.format("序号", "价格", "商品名称"))
	count = 0
	for g in ilt:
		count += 1
		print(tplt.format(count, g[0], g[1]))
def main():
	goods = 'iphone8'
	start_url = 'https://s.taobao.com/search?q=' + goods
	depth = 2
	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()

运行截图:

爬取淘宝商品

上一篇:

下一篇: