我想要一份爬取淘宝商品信息的python代码
时间: 2023-09-12 15:08:02 浏览: 42
爬取淘宝商品信息的python代码可以通过以下步骤实现:
1. 安装所需的库:requests、BeautifulSoup、re、json等。
2. 构造请求URL,其中包含了搜索关键字、排序方式、价格区间等信息。
3. 发送HTTP请求,获取搜索结果页面的HTML文本。
4. 使用BeautifulSoup解析HTML文本,获取商品信息。
5. 将商品信息存储到本地文件或数据库中。
下面是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
import re
import json
def get_taobao_items(keyword, price_low=0, price_high=9999999, sort='sale-desc', page=1):
url = "https://s.taobao.com/search?q={}&lowPrice={}&highPrice={}&sort={}&s={}"
url = url.format(keyword, price_low, price_high, sort, (page-1)*44)
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"}
r = requests.get(url, headers=headers)
r.encoding = r.apparent_encoding
html = r.text
soup = BeautifulSoup(html, 'html.parser')
items = soup.select('.item.J_MouserOnverReq')
result = []
for item in items:
item_info = {}
item_info['title'] = item.find('img')['alt']
item_info['price'] = float(item.select('.price')[0].text.strip())
item_info['url'] = 'https:'+item.select('.pic-link.J_ClickStat.J_ItemPicA')[0]['href']
item_info['img_url'] = 'https:'+item.select('.pic-link.J_ClickStat.J_ItemPicA img')[0]['src']
result.append(item_info)
return result
if __name__ == '__main__':
items = get_taobao_items('手机', price_high=3000, sort='renqi-desc')
print(json.dumps(items, ensure_ascii=False, indent=2))
```
这个示例代码可以实现搜索关键字为"手机",价格在0到3000元之间,按热度排序的淘宝商品信息爬取,并将结果以JSON格式输出。你可以根据自己的需要对代码进行修改和完善。