使用BeautifulSoup进行网页爬取时返回空列表的问题排查请求
解决BeautifulSoup爬取Empire电影页面返回空列表的问题
问题原因
该页面的电影标题是通过JavaScript动态渲染加载的,requests.get()只能获取页面初始的静态HTML源码,其中并不包含目标h3元素,因此调用find_all会返回空列表。
解决方案
方案一:解析页面内嵌的JSON数据(无需浏览器)
页面的电影数据通常会内嵌在script标签中,直接提取解析即可:
import requests import json from bs4 import BeautifulSoup url = "https://www.empireonline.com/movies/features/best-movies-2/" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") # 定位存储电影数据的script标签 script_tag = soup.find("script", id="__NEXT_DATA__") # 解析JSON格式数据 movie_data = json.loads(script_tag.string) # 提取所有电影标题 movies = movie_data["props"]["pageProps"]["data"]["getArticle"]["_items"][0]["props"]["movies"] title_list = [movie["title"] for movie in movies] # 打印结果 for idx, title in enumerate(title_list, 1): print(f"{idx}. {title}")
方案二:使用Selenium模拟浏览器加载动态内容
通过模拟真实浏览器的渲染过程,获取完整的页面内容:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager url = "https://www.empireonline.com/movies/features/best-movies-2/" # 初始化Chrome浏览器 driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) driver.get(url) # 定位所有目标h3元素 title_elements = driver.find_elements(By.CLASS_NAME, "jsx-4245974604") title_list = [elem.text for elem in title_elements] # 打印结果 for title in title_list: print(title) # 关闭浏览器 driver.quit()
注意事项
- 方案一效率更高,无需额外安装浏览器驱动,但需要准确找到数据在JSON结构中的位置;
- 方案二兼容性更强,能应对大多数动态渲染页面,但需要安装Selenium库及对应浏览器驱动。
内容的提问来源于stack exchange,提问作者Ittzsheldon
相关产品推荐
相关产品推荐

