Python 3.x 使用BeautifulSoup提取表行并将其与数据帧同步

Python 3.x 使用BeautifulSoup提取表行并将其与数据帧同步,python-3.x,pandas,web-scraping,beautifulsoup,Python 3.x,Pandas,Web Scraping,Beautifulsoup,我试图从以下网页中的表格中提取微笑字符串和重复单位的值: 虽然这可能不是最有效的方法,但我可以从以下代码中成功提取这些值: from bs4 import BeautifulSoup import requests link='https://khazana.gatech.edu/module_search/material_detail.php?id=1&m=9' link=requests.get(link) soup=BeautifulSoup(link.text) data

我试图从以下网页中的表格中提取微笑字符串和重复单位的值:

虽然这可能不是最有效的方法,但我可以从以下代码中成功提取这些值:

from bs4 import BeautifulSoup
import requests

link='https://khazana.gatech.edu/module_search/material_detail.php?id=1&m=9'
link=requests.get(link)
soup=BeautifulSoup(link.text)

data=[]
tables=soup.find_all('table')

#the desired table was selected based on list index because there is no other attributes
table_body=tables[9].find('tbody')
rows=table_body.findAll('tr')
for row in rows:
    cols=row.findAll('td')
    cols=[ele.text.strip() for ele in cols]
    data.append([ele for ele in cols if ele])

print (data[13][1])
print (data[14][1])
在我的应用程序中,我需要从类似网页的1000s中提取SMILES String和Repeat_Unit的值,其中html地址仅在id=后面出现的数字上不同,在本例中,id=是1

我有一个dataframe,其中一列具有数据的id。为了获得给定id的微笑字符串和重复单元,我将上述代码修改为:

data=[]
SMILES=[]
Repeat_Unit=[]
for index, prow in df.iterrows():
    a=prow['#id']
    link='https://khazana.gatech.edu/module_search/material_detail.php?id='+str(a)+'&m=9'
    link=requests.get(link)
    soup=BeautifulSoup(link.text)
    tables=soup.find_all('table')
    for table in tables:
        table_body=tables[9].find('tbody') 
        rows=table_body.findAll('tr')
        for row in rows:
            cols=row.findAll('td')
            cols=[ele.text.strip() for ele in cols]
            data.append([ele for ele in cols if ele])
            SMILES.append(data[13][1])
            Repeat_Unit.append(data[14][1])
现在,当我调用SMILES或RepeatUnit时,会出现以下错误:

IndexError                                Traceback (most recent call last)
<ipython-input-55-74f7ef016c59> in <module>()
     36             cols=[ele.text.strip() for ele in cols]
     37             data.append([ele for ele in cols if ele])
---> 38             SMILES.append(data[13][1])
     39             Repeat_Unit.append(data[14][1])

IndexError: list index out of range
索引器错误回溯(最近一次调用)
在()
36 cols=[ele.text.strip()表示cols中的ele]
37数据追加([ele表示列中的ele,如果ele])
--->38.追加(数据[13][1])
39重复单元。追加(数据[14][1])
索引器:列表索引超出范围
即使我在添加微笑之前遍历数据,我仍然会得到相同的错误

提前感谢您的帮助

使用:

s = ['SMILES String', 'Repeat Unit']
N = 10
data=[]

for a in np.arange(1,N + 1):
    link='https://khazana.gatech.edu/module_search/material_detail.php?id='+str(a)+'&m=9'
    link=requests.get(link)
    soup=BeautifulSoup(link.text, 'lxml')
    d = {}
    for x in s:
        #https://stackoverflow.com/a/5999786/2901002
        out = soup.find(text=x).parent.findNext('td').contents[0]
        d[x] = out
    data.append(d)

df=pd.DataFrame(数据)
打印(df)
重复单元\
0 C5O3(CH2-OH)-O-C5O3(CH2-OH)-O
1聚苯乙烯
2 CH2-CH(CH3)-CH2-CH(CH3)
3 CHF-CF2-CHF-CF2

4如果我使用你的第一段代码,我会得到一个错误。这是因为
没有
t正文
重复单元中的图像有问题,请检查。该值的预期值是什么?是否需要省略
SMILES字符串-重复单元
pair?还是将图像替换为空字符串?或者别的什么?但它在Python3上不起作用。当我对整个1000s数据项运行它时,它返回以下错误:--------------------------------------------------------------------------------------AttributeError Traceback(最近一次调用)in()27 for x in s:28#------->29 out=soup.find(text=x.parent.findNext('td')).contents[0]30 d[x]=out 31个数据。append(d)AttributeError:'NoneType'对象没有属性'parent'@A.E-这意味着没有值表单
s
列表,刚刚测试过,问题在于
https://khazana.gatech.edu/module_search/material_detail.php?id=253&m=9
@jezrael-I已经注意到没有id=253&m=9和id=308&m=9,并且已经通过在我的原始数据集中循环id来处理它,但它仍然返回此错误。你介意我把我的csv.file和jupityer笔记本寄给你吗?@jezrael谢谢!我就这么做了。
df = pd.DataFrame(data)
print (df)
                                         Repeat Unit  \
0                    C5O3(CH2-OH)-O-C5O3(CH2-OH)-O     
1                                      Polystyrene     
2                          CH2-CH(CH3)-CH2-CH(CH3)     
3                                  CHF-CF2-CHF-CF2     
4  <img border="0" height="60" src="block_images/...   
5                                CNS-C6H3-CSN-C6H3     
6                                    CH(CF3)-O-CH2     
7                                      (CH2)5-O-CO     
8                                CH2-CH2-C(CF3)2-O     
9  <img border="0" height="60" src="block_images/...   

                                       SMILES String  
0                            C(C(O)C1(O))C(CO)OC1O    
1  CC(C1=CC=CC=C1)CC(C2=CC=CC=C2)CC(C3=CC=CC=C3)C...  
2                                  CC(C)CC(C)CC(C)    
3                                      C(F)C(F)(F)    
4                           C(S1)=CC=C1C(S2)=CC=C2    
5           C(OC1=C2)=NC1=CC=C2C(OC3=C4)=NC3=CC=C4    
6                   C(C(F)(F)(F))OCC(C(F)(F)(F))OC    
7                           CCCCCOC(=O)CCCCCOC(=O)    
8  CCC(C(F)(F)(F))(C(F)(F)(F))OCCC(C(F)(F)(F))(C(...  
9                                             CCCC