简单爬取淘宝商品信息

'''requests 和re 库使用前需要对其进行安装
方法为:打开cmd(cmd是命令提示符)然后输入  pip install requests
安装完成后,在进行re的安装   pip install re
'''
import requests
import re
goods='书包'       #goods是需要搜索的商品名称
'''url 是 需要爬取的网页地址,获取到URL之后,用requests.get方法进行网页的爬取,timeout是时间'''
url='https://ai.taobao.com/search/index.htm?key='+goods
r=requests.get(url,timeout=30)     
r.raise_for_status()
r.encoding=r.apparent_encoding
print(r.status_code)	#打印状态码,如果为200则说明爬取成功,如状态码不清楚则可以参考本人其他博客中的状态码。
list=[]     #先构造一个空的列表,用来存放数据
title1=re.findall(r'\"title\":\".*?\"',r.text)   #运用正则表达式来获取需要的商品名称

price1=re.findall(r'\"salePrice\":\"[\d.]*\"',r.text)	#运用正则表达式来获取需要的商品价格

for i in range(0,len(price1)):
    title=eval(title1[i].split(':')[1])
    price=eval(price1[i].split(':')[1])

    list.append([title,price])		#将所有数据存储到列表中
print('{:^5}\t{:^5}\t{:<35}'.format('序号','价格','商品名称'))
count=1
for g in list:
    print('{:^5}\t{:^5}\t{:<35}'.format(count,g[1],g[0]))
    count+=1

此段代码并没有对爬虫进行深入解说,如果只是爬取商品来进行比对价格的话,还是比较有用的。下面为爬取结果。
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是Python爬取淘宝商品信息的基本思路: 1. 分析淘宝商品搜索面的HTML结构,确定需要爬取的数据,如商品标题、价格、销量、评论数、店铺名称等。 2. 使用Python的爬虫框架(如requests、Scrapy等)向淘宝商品搜索面发送请求,获取面HTML源代码。 3. 使用Python的HTML解析库(如BeautifulSoup、pyquery等)解析HTML源代码,获取需要的数据。 4. 将获取到的数据保存到本地文件或数据库中。 下面是一个简单Python爬取淘宝商品信息的示例代码: ```python import requests from bs4 import BeautifulSoup def get_taobao_info(keyword): url = 'https://s.taobao.com/search?q={}'.format(keyword) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'lxml') items = soup.select('.item.J_MouserOnverReq') for item in items: title = item.select('.title')[0].get_text().strip() price = item.select('.price')[0].get_text() sale = item.select('.deal-cnt')[0].get_text() shop = item.select('.shop')[0].get_text().strip() print('商品:{},价格:{},销量:{},店铺:{}'.format(title, price, sale, shop)) if __name__ == '__main__': keyword = '手机' get_taobao_info(keyword) ``` 这段代码实现了对淘宝商品搜索面的爬取,并输出商品的标题、价格、销量和店铺名称。你可以根据需要修改代码,获取更多商品信息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值