Python网页爬取问题:Trip Advisor评论数返回None
爬取Yellowpages商家Trip Advisor评论数量失败问题
问题现象
使用Python爬取Yellowpages洛杉矶餐厅页面的Trip Advisor评论数量时,代码输出全为None,无法获取页面显示的评论数字(对应元素截图:
)。
问题原因
Trip Advisor的评论数据是动态加载的,直接通过requests获取的静态HTML源码中并不包含ta-count类的元素,导致BeautifulSoup无法定位到目标内容。
解决方案
使用Selenium模拟浏览器加载动态页面,确保获取到完整的渲染后源码:
前置准备
- 安装Selenium库:
pip install selenium - 下载与本地Chrome浏览器版本匹配的ChromeDriver,并配置到系统环境变量中(或在代码中指定Driver路径)。
修正后的代码
from selenium import webdriver from selenium.webdriver.chrome.options import Options from bs4 import BeautifulSoup import time # 配置Chrome浏览器选项 chrome_options = Options() chrome_options.add_argument('--headless=new') # 无头模式,不显示浏览器窗口 chrome_options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36') chrome_options.add_argument('--disable-blink-features=AutomationControlled') # 避免被网站检测为自动化工具 # 初始化浏览器驱动 driver = webdriver.Chrome(options=chrome_options) target_url = "https://www.yellowpages.com/los-angeles-ca/restaurants?page=1" driver.get(target_url) # 等待动态内容加载完成(根据网络情况调整等待时间) time.sleep(3) # 获取渲染后的页面源码 page_html = driver.page_source soup = BeautifulSoup(page_html, 'html.parser') # 遍历商家结果 for result in soup.find_all('div', class_='result'): ta_count_elem = result.find("span", class_="ta-count") if ta_count_elem: # 提取并清理评论数字 comment_count = ta_count_elem.text.strip().strip('()') print(comment_count) else: print(None) # 关闭浏览器 driver.quit()
注意事项
- 若需要查看页面加载过程,可注释掉
--headless=new参数,显示浏览器窗口。 - 调整
time.sleep()的等待时长,确保动态数据完全加载。 - 定期检查ChromeDriver版本,保证与Chrome浏览器版本兼容。
内容的提问来源于stack exchange,提问作者Kbrosal
相关产品推荐
相关产品推荐

