page contents

Python通过正则库爬取淘宝商品信息代码实例

使用正则库爬取淘宝商品的商品信息,首先我们需要确定想要爬取的对象。 我们在淘宝里搜索“python”,出来的结果: 从url连接中可以得到搜索商品的关键字是“q=”,所以我们要用的起始url为:h...

使用正则库爬取淘宝商品的商品信息,首先我们需要确定想要爬取的对象。

我们在淘宝里搜索“python”,出来的结果:

v2-867cdafa3478375801cb9e108de18704_720w.jpg


从url连接中可以得到搜索商品的关键字是“q=”,所以我们要用的起始url为:https://s.taobao.com/search?q=python

然后翻页,经过对比发现,翻页后,变化的关键字是s,每次翻页,s便以44的倍数增长(可以数一下每页显示的商品数量,刚好是44)
所以可以根据关键字“s=”,来设置爬取的深度(爬取多少页)

右键查看源码,商品名称可能的关键字是“title”和“raw_title”,进一步多看几个商品的名称,发现选取“raw_title”比较合适;商品价格自然就是“view_price”(通过比对淘宝商品展示页面);所以商品名称和商品价格分别是以"raw_title":"名称"和"view_price":"价格",这样的键/值对的形式展示的。

# coding:utf-8
 
import requests
import re
 
goods = '水杯'
url = 'https://s.taobao.com/search?q=' + goods
 
r = requests.get(url=url, timeout=10)
html = r.text
 
tlist = re.findall(r'\"raw_title\"\:\".*?\"', html) # 正则提取商品名称
plist = re.findall(r'\"view_price\"\:\"[\d\.]*\"', html) # 正则提示商品价格
 
print(tlist)
print(plist)
print(type(plist)) # 正则表达式提取出的商品名称和商品价格都是以列表形式存储数据的

利用for循环,把每个商品的名称和价格组成一个列表,然后把这写列表再追加到一个大列表中:

goodlist = []
for i in range(len(tlist)):
title = eval(tlist[i].split(':')[1]) # eval()函数简单说就是用于去掉字符串的引号
price = eval(plist[i].split(':')[1])
goodlist.append([title, price]) # 把每个商品的名称和价格组成一个小列表,然后把所有商品组成的列表追加到一个大列表中
print(goodlist)

大概的思路就是这样的。

def get_html(url):
"""获取源码html"""
try:
r = requests.get(url=url, timeout=10)
r.encoding = r.apparent_encoding
return r.text
except:
print("获取失败")
def get_data(html, goodlist):
"""使用re库解析商品名称和价格
tlist:商品名称列表
plist:商品价格列表"""
tlist = re.findall(r'\"raw_title\"\:\".*?\"', html)
plist = re.findall(r'\"view_price\"\:\"[\d\.]*\"', html)
for i in range(len(tlist)):
title = eval(tlist[i].split(':')[1]) # eval()函数简单说就是用于去掉字符串的引号
price = eval(plist[i].split(':')[1])
goodlist.append([title, price])
 
 
def write_data(list, num):
# with open('E:/Crawler/case/taob2.txt', 'a') as data:
# print(list, file=data)
for i in range(num): # num控制把爬取到的商品写进多少到文本中
u = list[i]
with open('E:/Crawler/case/taob.txt', 'a') as data:
print(u, file=data)
 
 
def main():
goods = '水杯'
depth = 3 # 定义爬取深度,即翻页处理
start_url = 'https://s.taobao.com/search?q=' + goods
infoList = []
for i in range(depth):
try:
url = start_url + '&s=' + str(44 * i) # 因为淘宝显示每页44个商品,第一页i=0,一次递增
html = get_html(url)
get_data(html, infoList)
except:
continue
write_data(infoList, len(infoList))
if __name__ == '__main__':
main()
  • 发表于 2020-03-02 14:59
  • 阅读 ( 595 )
  • 分类:Python开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
Pack
Pack

1135 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1316 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章