python爬虫爬取优衣库评论实例
时间: 2025-06-01 12:57:47 浏览: 25
### 使用 Python 爬虫爬取优衣库评论
为了实现通过 Python 爬虫获取优衣库评论的功能,可以采用 `requests` 和 `BeautifulSoup` 的组合来抓取静态页面中的数据。如果目标网站依赖 JavaScript 动态加载内容,则可能需要借助 Selenium 来模拟浏览器行为。
以下是具体的技术方案以及代码示例:
#### 技术栈
- **Python 3**: 主要编程语言。
- **Requests**: 发送 HTTP 请求并获取 HTML 页面内容[^1]。
- **BeautifulSoup**: 解析 HTML 文档并提取所需数据[^1]。
- **Pandas**: 数据整理与存储。
- **Selenium (可选)**: 如果目标网站的内容由 JavaScript 渲染,则需使用此工具模拟浏览器操作[^1]。
#### 示例代码
假设优衣库的商品详情页 URL 已知,可以通过以下方式抓取其评论部分的数据。
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
def fetch_uniqlo_reviews(url, headers=None):
"""
获取优衣库商品评论数据
参数:
url (str): 商品详情页链接
headers (dict): 请求头信息
返回:
DataFrame: 包含评论的表格结构
"""
response = requests.get(url, headers=headers)
if response.status_code != 200:
raise Exception(f"无法访问URL {url}, 响应码: {response.status_code}")
soup = BeautifulSoup(response.text, 'html.parser')
reviews = []
# 查找评论区域
review_sections = soup.find_all('div', class_='review-section') # 替换为实际类名
for section in review_sections:
user_name = section.find('span', class_='username').text.strip() if section.find('span', class_='username') else None
rating = int(section.find('span', class_='rating')['data-value']) if section.find('span', class_='rating') else None
comment_text = section.find('p', class_='comment-text').text.strip() if section.find('p', class_='comment-text') else ''
reviews.append({
'用户名': user_name,
'评分': rating,
'评论内容': comment_text
})
df_reviews = pd.DataFrame(reviews)
return df_reviews
if __name__ == "__main__":
uniqlo_product_url = "https://example.com/uniqlo-product-page"
custom_headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36",
"Accept-Language": "en-US,en;q=0.9"
}
try:
reviews_df = fetch_uniqlo_reviews(uniqlo_product_url, headers=custom_headers)
print("成功抓取评论:")
print(reviews_df.head())
except Exception as e:
print(f"错误: {e}")
```
以上代码展示了如何从一个假定的目标页面中提取用户名称、评分和评论内容,并将其保存至 Pandas DataFrame 中以便后续分析或导出。
#### 注意事项
- 需确认目标网站的具体 DOM 结构(如 `class='review-section'`),这通常可通过开发者工具查看源代码获得。
- 若遇到反爬机制,建议设置合理的请求间隔时间或者更换 IP 地址以降低被封禁的风险。
- 对于动态渲染的网页,考虑引入 Selenium 并配置无头模式运行浏览器实例。
---
阅读全文
相关推荐


















