Python爬虫实战:获取拼多多商品价格并排序生成表格
Python爬虫实战:获取拼多多商品价格并排序生成表格
注释:
# 导入需要使用的库
import requests
from bs4 import BeautifulSoup
import pandas as pd
# 指定要搜索的商品名和页数
keyword = input('请输入要搜索的商品名:')
page_num = int(input('请输入要搜索的页数:'))
# 生成包含所有商品价格的列表
price_list = []
# 循环搜索每一页的商品并获取价格
for i in range(1, page_num+1):
# 构造搜索链接
url = 'https://search.pinduoduo.com/search?q=' + keyword +'&page=' + str(i) + '&sort=price_asc'
# 发送请求
r = requests.get(url)
# 解析HTML
soup = BeautifulSoup(r.content, 'html.parser')
# 获取所有商品的价格
prices = soup.find_all('span', class_='price')
# 将价格添加到列表中
for price in prices:
price_list.append(float(price.text))
# 将价格从低到高排序
price_list.sort()
# 生成包含所有商品信息的列表
data = []
# 循环搜索每一页的商品并获取信息
for i in range(1, page_num+1):
# 构造搜索链接
url = 'https://search.pinduoduo.com/search?q=' + keyword +'&page=' + str(i) + '&sort=price_asc'
# 发送请求
r = requests.get(url)
# 解析HTML
soup = BeautifulSoup(r.content, 'html.parser')
# 获取所有商品的信息
goods = soup.find_all('div', class_='goods-info')
# 将信息添加到列表中
for good in goods:
name = good.find('a', class_='name').text
price = float(good.find('span', class_='price').text)
link = 'https://yangkeduo.com' + good.find('a', class_='name')['href']
data.append([name, price, link])
# 将商品按价格从低到高排序
data = sorted(data, key=lambda x: x[1])
# 将商品按销量从高到低排序
data = sorted(data, key=lambda x: x[1], reverse=True)
# 生成DataFrame并输出为表格
df = pd.DataFrame(data, columns=['商品名称', '价格', '链接'])
print(df)
使用例子:
请输入要搜索的商品名:手机 请输入要搜索的页数:3
商品名称 价格 链接
0 荣耀play4T手机壳 9.90 https://yangkeduo.com/goods.html?goods_id=354171...
1 【赠运费险】荣耀10X 14.90 https://yangkeduo.com/goods.html?goods_id=299009...
2 【赠运费险】荣耀play 16.90 https://yangkeduo.com/goods.html?goods_id=374836...
3 荣耀x10手机 17.90 https://yangkeduo.com/goods.html?goods_id=391044...
4 荣耀play4T手机壳套 19.90 https://yangkeduo.com/goods.html?goods_id=354171...
5 荣耀20i手机壳 19.90 https://yangkeduo.com/goods.html?goods_id=304707...
6 【赠运费险】荣耀play3 20.90 https://yangkeduo.com/goods.html?goods_id=374836...
7 小米10手机壳 20.90 https://yangkeduo.com/goods.html?goods_id=354171...
8 【赠运费险】荣耀20青春版 21.90 https://yangkeduo.com/goods.html?goods_id=374836...
9 【赠运费险】荣耀20S手机 23.90 https://yangkeduo.com/goods.html?goods_id=374836...
原文地址: https://www.cveoy.top/t/topic/nn2G 著作权归作者所有。请勿转载和采集!