python爬取淘宝店铺货源
时间: 2023-11-23 13:57:59 浏览: 81
以下是使用Python爬取淘宝店铺货源的步骤:
1. 导入必要的库
```python
import requests
import re
```
2. 获取搜索页面HTML代码
```python
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
```
3. 解析搜索页面HTML代码,获取商品列表
```python
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]) # 将商品名称字符串转为Unicode编码
ilt.append([price, title])
except:
print("")
def getGoodsList(keywords):
goods = []
depth = 2 # 爬取深度
start_url = 'https://s.taobao.com/search?q=' + keywords
for i in range(depth):
try:
url = start_url + '&s=' + str(44*i)
html = getHTMLText(url)
parsePage(goods, html)
except:
continue
return goods
```
4. 输出商品列表
```python
def printGoodsList(goods):
tplt = "{:4}\t{:8}\t{:16}" # 表格模板
print(tplt.format("序号", "价格", "商品名称"))
count = 0
for g in goods:
count += 1
print(tplt.format(count, g[0], g[1]))
```
5. 调用函数并输出结果
```python
goods = getGoodsList('手机') # 搜索关键词为手机的商品
printGoodsList(goods)
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)