Skip to main content
 首页 » 编程设计

使用 beautifulsoup 进行 Python 网络抓取之无法从 Clinicaltrials.gov 中提取首席研究员

2025年05月04日19tintown

(免责声明:我是 Python 和网络抓取新手,但我正在尽我最大努力学习)。

我正在尝试从 clinicaltrials.gov 上的研究中提取 3 个关键数据点。他们有一个 API,但 API 没有捕获我需要的东西。我想获得 (1) 研究的简短描述,(2) 首席研究员 (PI),以及 (3) 与研究相关的一些关键词。我相信我的代码捕获了 1 和 3,但没有捕获 2。我似乎无法弄清楚为什么我没有得到首席研究员的名字。这是我的代码中的两个站点:

https://clinicaltrials.gov/ct2/show/NCT03530579 https://clinicaltrials.gov/ct2/show/NCT03436992

这是我的代码(我知道 PI 代码是错误的,但我想证明我试过了):

import pandas as pd 
import requests 
from bs4 import BeautifulSoup 
import csv    
 
fields=['PI','Project_Summary', 'Keywords'] 
with open(r'test.csv', 'a') as f: 
     writer = csv.writer(f) 
     writer.writerow(fields) 
 
urls = ['https://clinicaltrials.gov/ct2/show/NCT03436992','https://clinicaltrials.gov/ct2/show/NCT03530579'] 
for url in urls: 
 
     response = requests.get(url) 
     soup = BeautifulSoup(response.content, 'html.parser') 
     #get_keywords 
     for rows in soup.find_all("td"): 
          k = rows.get_text()      
          Keywords = k.strip() 
     #get Principal Investigator    
     PI = soup.find_all('padding:1ex 1em 0px 0px;white-space:nowrap;') 
 
     #Get description     
     Description = soup.find(class_='ct-body3 tr-indent2').get_text() 
     d = {'Summary2':[PI,Description,Keywords]}  
 
     df = pd.DataFrame(d) 
     print (df) 
     import csv    
     fields=[PI,Description, Keywords] 
     with open(r'test.csv', 'a') as f: 
          writer = csv.writer(f) 
          writer.writerow(fields) 

请您参考如下方法:

您可以使用以下选择器

即PI = soup.select_one('.tr-table_cover [headers=name]').text

import requests 
from bs4 import BeautifulSoup   
urls = ['https://clinicaltrials.gov/ct2/show/NCT03530579', 'https://clinicaltrials.gov/ct2/show/NCT03436992','https://clinicaltrials.gov/show/NCT03834376'] 
with requests.Session() as s: 
    for url in urls: 
        r = s.get(url) 
        soup = BeautifulSoup(r.text, "lxml") 
        item = soup.select_one('.tr-table_cover [headers=name]').text if soup.select_one('.tr-table_cover [headers=name]') is not None else 'No PI' 
        print(item) 

. 是一个 class selector [] 是 attribute选择器。之间的空间是 descendant combinator指定右侧检索到的元素是左侧元素的子元素