Python-使用requests库和正则表达式爬取淘宝商品信息
〇、环境
语言版本:python 3.8.3
编辑器:IDLE(python自带)
操作系统:win10
一、需求
1、获取taobao指定商品页面中的 价格和名称,这里以书包为例子。

2、格式化输出

二、分析
1、taobao商品页面的源代码组织形式
在商品页右键查看源代码,然后根据商品价格和商品名搜索,会发现 商品名前有“raw_title”键,价格前有“view_price”键;
依此,获取本页面的html之后,我们可以很方便的用正则表达式获取想要信息。

2、障碍及其解决
淘宝的反爬虫机制,会使得未登录则不可访问,所以我们得先登录,并获取cookie

三、编码实现
0、引入需要的库
import requests
import re
#requests库是网络请求库,需要提前安装(在命令行窗口以:pip install requests)
1、获取商品页的html代码
def getHTMLText(url):
try:
#本header中需要有cookie和user-agent字段
#cookie是为了模拟登录,user-agent是为了模拟某些浏览器发起的请求
header = {‘cookie‘:‘刚刚获取的cookie复制到此‘,‘user-agent‘:‘Mozilla/5.0‘}
r = requests.get(url,timeout=30,headers = header)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""2、处理html代码,获取商品信息
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("")3、格式化打印输出
def printGoodsList(ilt):
#使用format()函数,格式话打印
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])) 相关推荐
wangzhaotongalex 2020-10-20
wyq 2020-11-11
TLROJE 2020-10-26
风雨断肠人 2020-10-13
duanqingfeng 2020-09-29
rechanel 2020-11-16
luofuIT成长记录 2020-09-22
phphub 2020-09-10
taomengxing 2020-09-07
MaggieRose 2020-08-19
flyingssky 2020-08-18
山水沐光 2020-08-18
jyj00 2020-08-15
AHuqihua 2020-08-09
山水沐光 2020-08-03