You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UniProt搜索结果Entry ID提取失败求助(偏好非API方案)

问题原因及解决方案

1. 核心问题分析

  • 请求头缺失:UniProt服务器会校验请求的User-Agent字段,缺失该字段时,返回的HTML结构会和浏览器端展示的不一致,导致搜索结果元素未被加载。
  • 动态class不可靠:你依赖的BqBnJ是前端框架动态生成的类名,这类名称会随页面更新随时变化,不能作为稳定的定位依据。

修正后的静态爬取代码

import requests
from bs4 import BeautifulSoup

url = "https://www.uniprot.org/uniprotkb?query=wound+healing"
# 添加模拟浏览器的请求头,避免被服务器识别为爬虫
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}

res = requests.get(url, headers=headers)
res.raise_for_status()
soup = BeautifulSoup(res.text, "html.parser")

# 改用href属性特征定位:所有Entry ID链接都遵循 /uniprotkb/{ID}/entry 格式
links = soup.find_all("a", href=lambda x: x and x.startswith('/uniprotkb/') and x.endswith('/entry'))

uniprot_ids = [link.get_text(strip=True) for link in links]
for uniprot_id in uniprot_ids:
    print(uniprot_id)

关键说明

  • 请求头作用:添加User-Agent让服务器认为请求来自正常浏览器,返回完整的搜索结果结构。
  • 稳定选择器:放弃动态类名,通过链接的固定格式特征定位元素,这个规则不会轻易变更。
  • 验证方法:可以把res.text保存为本地HTML文件,打开后查看实际元素结构,确认选择器是否匹配。

动态加载场景的解决方案(若静态爬取仍失效)

如果页面完全由JavaScript动态渲染,静态请求无法获取结果,可使用selenium模拟浏览器加载:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time

url = "https://www.uniprot.org/uniprotkb?query=wound+healing"
# 配置无头模式(不弹出浏览器窗口)
chrome_options = Options()
chrome_options.add_argument("--headless=new")

driver = webdriver.Chrome(options=chrome_options)
driver.get(url)
# 等待页面加载完成
time.sleep(3)

# 用CSS选择器匹配符合格式的链接
links = driver.find_elements(By.CSS_SELECTOR, 'a[href^="/uniprotkb/"][href$="/entry"]')
uniprot_ids = [link.text.strip() for link in links]

for uniprot_id in uniprot_ids:
    print(uniprot_id)

driver.quit()

注:使用此方法需提前安装selenium库及对应浏览器的驱动(如ChromeDriver)。

内容的提问来源于stack exchange,提问作者SH Kim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 05:20:56