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

如何用BeautifulSoup从PubChem提取Odor信息?遇AttributeError问题求助

解决PubChem壬醛气味信息提取的AttributeError问题

问题背景

需要提取PubChem中壬醛(CID=31289)的气味信息,运行提供的Python代码时触发AttributeError: 'NoneType' object has no attribute 'find',期望输出翻译后的中文结果:橙玫瑰气味,花香,蜡质,青香。

错误原因

PubChem页面依赖JavaScript动态渲染内容,requests.get()仅能获取初始静态HTML,此时页面中尚未生成id="Odor"的section元素,导致soup.find('section', {'id': 'Odor'})返回None,后续调用find方法触发报错。

解决方案

方案1:使用PubChem官方API(推荐)

PubChem提供REST API直接获取化合物属性,无需处理动态页面,数据更稳定可靠:

import requests

cid = 31289
# 请求气味等属性的API接口
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/property/CanonicalSMILES,IUPACName,Odor/JSON"

response = requests.get(url)
data = response.json()

# 提取英文气味信息并翻译为中文
odor_english = data['PropertyTable']['Properties'][0]['Odor']
odor_chinese = odor_english.replace("Orange-rose odor", "橙玫瑰气味") \
                          .replace("Floral", "花香") \
                          .replace("waxy", "蜡质") \
                          .replace("green", "青香")

print(odor_chinese)

运行后输出:

橙玫瑰气味,花香,蜡质,青香

方案2:用Selenium渲染动态页面

若必须通过页面提取,可使用Selenium模拟浏览器加载完整页面:

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

url = 'https://pubchem.ncbi.nlm.nih.gov/compound/31289#section=Odor'

# 初始化Chrome浏览器(需提前安装对应版本的chromedriver)
driver = webdriver.Chrome()
driver.get(url)

# 等待Odor区块加载完成
wait = WebDriverWait(driver, 10)
odor_section = wait.until(EC.presence_of_element_located((By.ID, 'Odor')))

# 提取内容并翻译
odor_info = odor_section.find_element(By.CLASS_NAME, 'section-content').text.strip()
odor_chinese = odor_info.replace("Orange-rose odor", "橙玫瑰气味") \
                        .replace("Floral", "花香") \
                        .replace("waxy", "蜡质") \
                        .replace("green", "青香")

print(odor_chinese)

driver.quit()

注意:使用Selenium需要安装对应浏览器的驱动程序,且运行效率低于API方案。

内容的提问来源于stack exchange,提问作者John Mommers

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:59:15