You need to enable JavaScript to run this app. 使用requests+BeautifulSoup爬取网站评论失败,求解决方案
优惠活动
大模型
产品
解决方案
定价
更多

使用requests+BeautifulSoup爬取网站评论失败,求解决方案

爬取问题排查及解决方案

现有代码存在的问题

  • 未携带请求头发送请求:你已经定义了headers请求头参数,但调用requests.get()时没有传入该参数,站点会直接识别到爬虫请求,返回不包含有效内容的响应。
  • 评论内容为动态渲染生成:目标站点的用户评论是通过JavaScript异步加载后渲染到页面的,初始静态HTML响应中不存在你要抓取的p.text标签内容,直接解析初始响应自然无法拿到对应数据。

修复方案

临时验证第一步:补充请求头参数

你可以先修改请求代码,补充传入headers,测试是否能拿到静态内容:

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/92.0.4515.131 Safari/537.36'
}
# 新增headers参数传入
r = requests.get('https://www.realpatientratings.com/botox-cosmetic', headers=headers) 
soup = BeautifulSoup(r.content, 'lxml')
tag = soup.find_all('p',class_='text')
for u in tag:
    print(u.text)

如果运行后还是无输出,就说明评论为动态加载,需要使用模拟浏览器的方案抓取。

最终可行方案:使用Selenium模拟浏览器加载动态内容

直接用Selenium启动无头浏览器,等待页面JS执行完成后再解析内容,代码如下:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import time

chrome_options = Options()
# 启用无头模式,不弹出浏览器窗口
chrome_options.add_argument('--headless')
chrome_options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36')

driver = webdriver.Chrome(options=chrome_options)
driver.get('https://www.realpatientratings.com/botox-cosmetic')
# 等待3秒保证异步内容加载完成,可根据网络情况调整时长
time.sleep(3)

soup = BeautifulSoup(driver.page_source, 'lxml')
tag = soup.find_all('p', class_='text')
for u in tag:
    print(u.text)

driver.quit()

运行前需要提前安装对应依赖:pip install selenium,同时要配置和你本地Chrome版本匹配的ChromeDriver。

内容的提问来源于stack exchange,提问作者Arslan Aziz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 16:30:00