python爬取淘宝商品信息
时间: 2023-09-01 13:10:35 浏览: 36
以下是使用Python爬取淘宝商品信息的基本步骤:
1. 导入所需库
```python
import requests
from bs4 import BeautifulSoup
```
2. 构造请求URL
淘宝商品搜索URL格式为:https://s.taobao.com/search?q=xxx,其中“xxx”为搜索关键词,需要把关键词转换为URL编码格式。例如,要搜索“手机”,则请求URL应该为:
```python
url = 'https://s.taobao.com/search?q=%E6%89%8B%E6%9C%BA'
```
3. 发送请求获取页面内容
```python
response = requests.get(url)
html = response.text
```
4. 解析页面内容
使用BeautifulSoup库解析页面内容,获取商品信息。例如,获取商品名称、价格和销量:
```python
soup = BeautifulSoup(html, 'html.parser')
items = soup.find_all('div', class_='item J_MouserOnverReq ')
for item in items:
title = item.find('div', class_='title').text.strip()
price = item.find('div', class_='price g_price g_price-highlight').text.strip()
sales = item.find('div', class_='deal-cnt').text.strip()
print(title, price, sales)
```
完整代码如下:
```python
import requests
from bs4 import BeautifulSoup
keyword = '手机'
url = 'https://s.taobao.com/search?q=' + keyword
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
items = soup.find_all('div', class_='item J_MouserOnverReq ')
for item in items:
title = item.find('div', class_='title').text.strip()
price = item.find('div', class_='price g_price g_price-highlight').text.strip()
sales = item.find('div', class_='deal-cnt').text.strip()
print(title, price, sales)
```
注意:淘宝反爬虫机制比较严格,可能会出现验证码等情况,需要相应的处理。另外,爬取淘宝商品信息需要遵守相关法律法规,不得用于商业用途。