BeautifulSoup爬取美国国家美术馆搜索结果无法获取条目链接如何解决
问题原因
你直接通过requests.get()拿到的是网站初始静态HTML,该站点的搜索结果是页面加载完成后通过异步接口拉取、客户端动态渲染生成的,所以直接解析初始HTML无法获取到目标藏品链接。
解决方案1:直接调用搜索接口(推荐)
这种方式无需渲染页面,请求效率更高。美国国家美术馆的藏品搜索有公开的JSON接口,直接请求该接口即可拿到结构化的藏品数据,拼接得到目标链接,实现代码如下:
import requests # 配置请求头模拟浏览器,避免被站点拦截 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" } # 藏品搜索接口地址 search_api = "https://www.nga.gov/bin/ngaweb/collection-search" # 构造搜索参数 params = { "artist": "Cézanne, Paul", "pageSize": 100, # 单页返回藏品数量,可按需调整 "pageNumber": 1 } # 发送请求获取结构化数据 response = requests.get(search_api, headers=headers, params=params) search_data = response.json() # 拼接生成藏品链接 art_urls = [] for item in search_data["artObjects"]: obj_id = item["objectId"] art_urls.append(f"https://www.nga.gov/collection/art-object-page.{obj_id}.html") # 验证输出前两个结果 print(art_urls[0]) print(art_urls[1])
解决方案2:使用浏览器渲染工具获取动态页面
如果不想排查接口规则,可使用Selenium、Playwright等工具模拟浏览器运行,等待页面完全渲染后再解析源码,实现代码如下:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup target_url = 'https://www.nga.gov/collection-search-result.html?artist=C%C3%A9zanne%2C%20Paul' # 初始化Chrome浏览器,需提前安装对应版本的ChromeDriver driver = webdriver.Chrome() driver.get(target_url) # 等待藏品链接元素加载完成,最长等待10秒 WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.artwork a'))) # 读取渲染完成的页面源码进行解析 soup = BeautifulSoup(driver.page_source, 'html.parser') driver.quit() # 提取藏品链接并补全前缀 art_urls = [] for a_tag in soup.select('.artwork a'): href = a_tag.get('href', '') if 'art-object-page' in href: full_url = f"https://www.nga.gov{href}" if href.startswith('/') else href art_urls.append(full_url)
内容的提问来源于stack exchange,提问作者Sanya Pushkar
相关产品推荐
相关产品推荐

