Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 熊猫和靓汤:打印href而不是列的值_Pandas_Beautifulsoup - Fatal编程技术网

Pandas 熊猫和靓汤:打印href而不是列的值

Pandas 熊猫和靓汤:打印href而不是列的值,pandas,beautifulsoup,Pandas,Beautifulsoup,这与网站上的其他帖子非常相似,例如,我就是看不出我做错了什么 我想在第页上刮掉标有“活动”的框,并希望输出如下所示: 因此,与原始网页相比,您可以看到两个感兴趣的主要功能:(1)将多个表合并到一个表中,如果尚未看到该列,只需创建一个新列;(2)我想提取该列的实际href,而不仅仅是名称,例如“Jacobsen et al”,因为我最终要从href中提取PMID值(一个整数) 这是我的两个目标,我写了以下代码: import requests import pandas as pd from b

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

我想在第页上刮掉标有“活动”的框,并希望输出如下所示:

因此,与原始网页相比,您可以看到两个感兴趣的主要功能:(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列)


然后我可以试着把注意力集中在如何组合这些表上,我刚才提到了最终目标,以防有人能想出一种更为通俗的方法,一石二鸟/以防有帮助,但我认为它们是不同的问题

您可以初始化最终数据帧。然后在迭代时,将
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)

我可以问一下,当我运行上述代码时,但我在final_df.iterrows()中的索引行末尾添加了:print(row['ref']),它为所有条目打印一个href(即表中观察到的第一个href)。我试着调试这个(你可能已经看到我之前的评论,当我认为我弄明白的时候,我删除了它),你对此有什么想法吗?我想这是因为href是按表设置的,而不是按行设置的,这就是我试图解决的问题。更正href是按表设置的。但是我可以,;如果我看不到你是如何实现的,我就不会调试这个问题。