给我一个完整的利用python爬取天猫数据
时间: 2024-03-13 17:45:13 浏览: 16
好的,以下是一个利用 Python 爬取天猫数据的完整代码示例:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头,模拟浏览器请求
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'}
# 定义爬取天猫商品信息的函数
def get_tmall_goods(keyword):
# 构造请求的url链接
url = 'https://list.tmall.com/search_product.htm?q=' + keyword
# 发送请求,获取响应内容
response = requests.get(url, headers=headers)
html = response.text
# 使用BeautifulSoup解析html
soup = BeautifulSoup(html, 'html.parser')
items = soup.select('.product .product-iWrap')
# 遍历每个商品,获取商品名称、价格、链接等信息
for item in items:
name = item.select('.productTitle a')[0].text.strip()
price = item.select('.productPrice em')[0].text.strip()
link = item.select('.productTitle a')[0]['href']
# 打印商品信息
print(name, price, link)
# 调用函数,搜索商品信息
get_tmall_goods('手机')
```
在上面的代码中,我们首先设置了请求头,模拟浏览器请求,避免被反爬虫机制拦截。然后定义了一个 get_tmall_goods 函数,该函数接收一个关键词作为参数,然后构造请求url链接,发送请求,获取响应内容,最后使用 Beautiful Soup 解析 html,遍历每个商品,获取商品名称、价格、链接等信息,然后打印出来。最后调用该函数,输入关键词,即可爬取对应的商品信息。