以下是用Python实现爬取Amazon产品评论的基本步骤:

  1. 安装必要的库

需要安装requests和beautifulsoup4库,可以使用pip命令安装:

pip install requests
pip install beautifulsoup4
  1. 获取产品页面的HTML代码

使用requests库向Amazon发送HTTP请求,获取产品页面的HTML代码:

import requests

url = 'https://www.amazon.com/dp/B01J94SWWU'
response = requests.get(url)
html = response.text

其中,url是要爬取的Amazon产品页面的URL。

  1. 解析HTML代码

使用beautifulsoup4库解析HTML代码,并获取评论部分的HTML代码:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')
reviews = soup.find_all('div', {'class': 'review'})

其中,find_all()方法用于查找所有class为“review”的div标签。

  1. 提取评论数据

遍历评论部分的HTML代码,提取评论数据,包括评论内容、评分、评论日期等:

for review in reviews:
    # 提取评论内容
    content = review.find('span', {'data-hook': 'review-body'}).text.strip()
    # 提取评分
    rating = review.find('i', {'data-hook': 'review-star-rating'}).text.strip().split()[0]
    # 提取评论日期
    date = review.find('span', {'data-hook': 'review-date'}).text.strip()
    # 打印评论数据
    print('Content: {}\nRating: {}\nDate: {}\n'.format(content, rating, date))

其中,text属性用于获取标签内的文本内容,strip()方法用于去除文本前后的空格和换行符。

完整的代码如下所示:

import requests
from bs4 import BeautifulSoup

url = 'https://www.amazon.com/dp/B01J94SWWU'
response = requests.get(url)
html = response.text

soup = BeautifulSoup(html, 'html.parser')
reviews = soup.find_all('div', {'class': 'review'})

for review in reviews:
    content = review.find('span', {'data-hook': 'review-body'}).text.strip()
    rating = review.find('i', {'data-hook': 'review-star-rating'}).text.strip().split()[0]
    date = review.find('span', {'data-hook': 'review-date'}).text.strip()
    print('Content: {}\nRating: {}\nDate: {}\n'.format(content, rating, date))
``
请给我用python写一个爬取amazon产品评论

原文地址: https://www.cveoy.top/t/topic/hiT7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录