【问题标题】:Pandas and beautiful soup: print href instead of the value for a column熊猫和美丽的汤:打印 href 而不是列的值
【发布时间】:2019-10-15 14:52:42
【问题描述】:

这与 SO 上的其他帖子非常相似,例如here,我就是看不出我做错了什么。

我想在this 页面上抓取标记为“活动”的框,并且我希望输出如下所示:

因此,您可以看到与原始网页相比感兴趣的两个主要功能 (1) 将多个表合并到一个表中,如果该列还没有看到,只需创建一个新列;(2) 我想提取该列的实际href,而不仅仅是名称,例如'Jacobsen et al' 因为我最终要从 href 中提取 PMID 值(一个整数)。

这是我的两个目标,我写了这段代码:

import requests
import pandas as pd
from bs4 import BeautifulSoup

for i in range(23,24):
#    try:
        res = requests.get("http://www.conoserver.org/index.php?page=card&table=protein&id=" + str(i))
        soup = BeautifulSoup(res.content, 'lxml')
        table = soup.find_all('table',{'class':'activitytable'})
        for each_table in table:

            #this can print references
            print(each_table.a)

            #this can print the data frames
            df = pd.read_html(str(each_table))
            print(df)

            #how to combine the two?

有人能告诉我为每个表的每一行单独打印 href 的正确方法(例如,本质上它会为每个表添加一个带有实际 href 的额外列吗?;所以它应该打印出三个表,一个额外的每个表中的href列)

然后我可以尝试专注于如何组合表格,我刚刚在这里提到了最终目标,以防有人可以想到一种更蟒蛇式的方式来用一块石头杀死两只鸟/以防它有帮助,但我认为他们'是不同的问题。

【问题讨论】:

    标签: pandas beautifulsoup


    【解决方案1】:

    您可以初始化最终数据帧。然后在您迭代时,将href 存储为变量字符串,然后将该列添加到子表数据框。然后,您将继续将这些数据帧附加到最终数据帧:

    import requests
    import pandas as pd
    from bs4 import BeautifulSoup
    
    # Initalized empty "final" dataframe
    final_df = pd.DataFrame()
    for i in range(20,24):
    #    try:
            res = requests.get("http://www.conoserver.org/index.php?page=card&table=protein&id=" + str(i))
            soup = BeautifulSoup(res.content, 'lxml')
            table = soup.find_all('table',{'class':'activitytable'})
            for each_table in table:
    
                #Store the href
                href = each_table.a['href']
    
                #Get the table
                df = pd.read_html(str(each_table))[0]
    
                #Put that href in the column 'ref'
                df['ref'] = href
    
                # Append that dataframe into your final dataframe, and repeat
                final_df = final_df.append(df, sort=True).reset_index(drop=True)
    

    【讨论】:

    • 请问,当我运行上面的代码时,我在最后添加了'for index,row in final_df.iterrows(): print(row['ref']),它会打印所有条目的一个href(即表中观察到的第一个href)。我试图调试这个(你可能已经看到了我之前的评论,当我认为我想通了时我删除了),你对此有什么想法吗?我想这是因为 href 是按表而不是按行设置的,这就是我要解决的问题。
    • 更正 href 是每个表。但是,如果我看不到您是如何实现的,我无法调试该问题。
    猜你喜欢
    • 2021-09-12
    • 2021-06-05
    • 1970-01-01
    • 2018-05-08
    • 2016-12-18
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多