如何使用python web抓取从列表中为每个输入提取html文本输出为列表。我已经编写了代码,但只给出了第一个条目输出

2024-04-20 10:49:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python和编程新手。我正试图从名为IMPAAT(https://cb.imsc.res.in/imppat/home)的数据库中提取pubchem ID。我有一个药草数据库中的化学ID列表,每个化学ID的超链接都提供了其pubchem ID和smiles数据的详细信息

我用python编写了一个脚本,将每个化学品ID作为输入,从html页面中查找pubchem ID,并使用API webscraping方法将输出打印到文本文件中

我发现很难将所有数据作为输出。非常肯定for循环中存在一些错误,因为它多次只打印第一个输出,而不是每个输入的不同输出

请帮忙

另外,我不知道如何保存这样的文件,它将输入和相应的输出并排打印。请帮忙

import requests
import xmltodict
from pprint import pprint
import time
from bs4 import BeautifulSoup
import json
import pandas as pd
import os
from pathlib import Path
from tqdm.notebook import tqdm

cids = 'output.txt'

df = pd.read_csv(cids, sep='\t')
df

data = []

for line in df.iterrows():
    
out = requests.get(f'https://cb.imsc.res.in/imppat/Phytochemical-detailedpage-auth/CID%{line}')
    
    soup = BeautifulSoup(out.text, "html.parser")
    
    if soup.status_code == 200:
        script_data = soup.find('div', {'class': 'views-field views-field-Pubchem-id'}).find('span', {'class': 'field-content'}).find('h3')
    #print(script_data.text)
    
    for text in script_data:
        
        texts = script_data.get_text()
        
        print(text)
    
    data.append(text)
   
    
print(data)
    

****
input file consists of 

cids
0   3A155934
1   3A117235
2   3A12312921
3   3A12303662
4   3A225688
5   3A440966
6   3A443160 ```

Tags: textinfromimportidfielddffor
1条回答
网友
1楼 · 发布于 2024-04-20 10:49:01

代码中几乎没有需要更正的内容

  1. out变量的缩进不正确

  2. 应该在响应对象上检查状态代码,即out而不是soup

  3. 您不需要第二个循环,因为每个响应只包含一个pubchem ID,您已经在script_data变量中收集到该ID

  4. 最后,您可以使用pandas将每个化学品ID与其pubchem ID关联,然后可以写入CSV文件

有关完整结果,请参阅以下代码

代码

import requests
import xmltodict
from pprint import pprint
import time
from bs4 import BeautifulSoup
import json
import pandas as pd
import os
from pathlib import Path
from tqdm.notebook import tqdm

cids = 'output.txt'

df = pd.read_csv(cids, sep='\t')

pubchem_id= []

for line in df.iterrows():
    
    out = requests.get(f'https://cb.imsc.res.in/imppat/Phytochemical-detailedpage-auth/CID%{line}')

    if out.status_code == 200:
        
        soup = BeautifulSoup(out.text, "html.parser")

        script_data = soup.find('div', {'class': 'views-field views-field-Pubchem-id'}).find('span', {'class': 'field-content'}).find('h3').getText()
    
        script_data = script_data.replace('PubChem Identifier:','')
        
        pubchem_id.append(script_data)

# As you have not mentioned column index of cids, I am assuming it should be the first column
df1 = pd.DataFrame({"chemical_id": df.iloc[:, 0].tolist(), "pubchem_id": pubchem_id})
    
print(df1)

# uncomment below line to write the dataframe into csv files & replace 'filename' by the complete filepath
# df1.to_csv('filename.csv')

相关问题 更多 >