Python如何通过正则库爬取淘宝商品信息

发布时间:2021-07-24 09:19:17 作者:小新
来源:亿速云 阅读:164

小编给大家分享一下Python如何通过正则库爬取淘宝商品信息,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

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

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

Python如何通过正则库爬取淘宝商品信息

从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()

以上是“Python如何通过正则库爬取淘宝商品信息”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. Python基于BeautifulSoup如何爬取京东商品信息
  2. Python中如何使用selenium爬取淘宝商品信息

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:.NET怎么动态加载用户控件并传值

下一篇:如何通过实例解析python描述符原理作用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》