StevenSun空间 2020-05-30
语言版本:python 3.8.3
编辑器:IDLE(python自带)
操作系统:win10


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

淘宝的反爬虫机制,会使得未登录则不可访问,所以我们得先登录,并获取cookie

import requests
import re
#requests库是网络请求库,需要提前安装(在命令行窗口以:pip install requests)
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 ""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):
#使用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]))