爬虫淘宝商品名称和价格
时间: 2023-12-17 17:43:33 浏览: 30
你可以使用 Python 编写爬虫来获取淘宝商品的名称和价格。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
def get_taobao_product_info(keyword):
url = f'https://s.taobao.com/search?q={keyword}'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36'
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
product_list = soup.find_all('div', class_='item J_MouserOnverReq')
for product in product_list:
name = product.find('a', class_='J_ClickStat').text.strip()
price = product.find('div', class_='price g_price g_price-highlight').text.strip()
print(f'商品名称:{name},价格:{price}')
keyword = input('请输入要搜索的关键词:')
get_taobao_product_info(keyword)
```
这段代码使用了 requests 库发送 HTTP 请求,使用 BeautifulSoup 库解析 HTML 页面。你需要安装这两个库,可以使用以下命令进行安装:
```
pip install requests beautifulsoup4
```
运行代码后,输入你想要搜索的关键词,代码将会输出相应商品的名称和价格。请注意,根据淘宝网站的反爬虫机制变化,代码可能需要进行相应的调整。