Python BeautifulSoup4和Pandas,按照表中的链接下载另一个表,将表连接到一个数据帧中

Python BeautifulSoup4和Pandas,按照表中的链接下载另一个表,将表连接到一个数据帧中,python,pandas,beautifulsoup,Python,Pandas,Beautifulsoup,注:问题和代码已被大量编辑,与之前一样 在我最初的帖子中出现了错误,我尝试了建议的答案,但都失败了 这些值被放置在数据帧的一列中 我的回答如下: 现在我可以得到第一个表,但在“更多”列中有一个链接,所以我尝试了这个答案: 我的剧本: """ get knapsack food table and table at link "more" """ import pandas as pd from bs4 import

注:问题和代码已被大量编辑,与之前一样 在我最初的帖子中出现了错误,我尝试了建议的答案,但都失败了 这些值被放置在数据帧的一列中

我的回答如下:

现在我可以得到第一个表,但在“更多”列中有一个链接,所以我尝试了这个答案: 我的剧本:

"""
get knapsack food table and table at link "more"
"""

import pandas as pd
from bs4 import BeautifulSoup
import requests
import lxml.html as lh
from langdetect import detect

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
url = "http://www.knapsackfamily.com/LunchBox/top.php"

#prepend to links
def prepend(arr, str):
    str += '{0}'
    arr = [str.format(i) for i in arr]

    return arr

# data for first post request    
data={
    #hidden type values and submit name and value
    'mode': 'list3',
    'fword1': '',
    'model': ' List All'
}

soup = BeautifulSoup(requests.post(url, data=data).content, 'html.parser')

stuff = []
for row in soup.select('table.sortable.d1 tr'):
    tds = [td.get_text(strip=True) for td in row.select('td, th')]
    stuff.append(tds)

for i in range(10):
    print(stuff[i])

#stuff[0] are the headers
# make dataframe and concantenate the next results 

# follow links
links = []
for link in soup.find_all('a', href=True):
    if link['href'].startswith('list'):
        links.append(link['href'])



url_prefix = "http://www.knapsackfamily.com/LunchBox/"
links_arr = prepend(links, url_prefix )
#visit links and get the cells I want:
en_pages = []
count = 0
print('here')
for link in links_arr:
    print(f'count: {count}\nlink: {link}\n')
    response = requests.get(link)

    soup_next = BeautifulSoup(response.content, 'html.parser')

    en_pages.append(soup_next)
    count+=1
    if count > 5:
        break

en_stuff = []
for page in en_pages:
    for row in page.select('table.rs2 tr'):
        tds = [td.get_text(strip=True) for td in row.select('td, th')]
        en_stuff.append(tds)
        
       
# filter English tables later


#if row in English
#if detec(row_text)=='en':
 #   en_stuff.append(row_text)
print("raw rows")
for table in en_stuff:
    print(table)

print("df's")
df_arr = []
count = 0
for table in en_stuff:
    next_pg_df = pd.DataFrame(table)
    df_arr.append(next_pg_df)
    print(next_pg_df)
    count+=1
    if count > 5:
        break

我把它限制在5,这样我就可以看到发生了什么。 “原始行”的输出为:

['大分類', '植物', 'Kingdom', 'Plant']
['種名', 'Abelmoschus esculentus', 'Species', 'Abelmoschus esculentus']
['学名(一般名)', 'Abelmoschus esculentus[okra、おくら、オクラ、秋葵、あめりかねり、アメリカネリ、おかれんこん、オカレンコン、陸蓮根]', 'Latin Name(General Name)', 'Abelmoschus esculentus[okra]']
['科名', 'アオイ科', 'Family', 'Malvaceae']
['原産/分布', '東北アフリカアフリカエチオピア近辺が原産。', 'Origin', 'Origins:Northeastern AfricaAfricaaround Ethiopia']
.
.
.
因此,如果我将第三个元素作为数据框列名,将第四个元素作为该列中第一个有机体的值,然后将第四个元素添加为后续有机体的列值,我可以创建一个数据框。
“df”的输出看起来不正确,因为它将所有内容都放在一列中:

         0
0      大分類
1       植物
2  Kingdom
3    Plant
                        0
0                      種名
1  Abelmoschus esculentus
2                 Species
3  Abelmoschus esculentus
                                                   0
0                                            学名(一般名)
1  Abelmoschus esculentus[okra、おくら、オクラ、秋葵、あめりかねり、...
2                           Latin Name(General Name)
3                       Abelmoschus esculentus[okra]
           0

有更好的方法吗?

在第一个解决方案的最后一行,而不是打印列表从列表中创建数据帧:

df = pd.DataFrame(en_stuff)

谢谢你的建议,我编辑了我的问题以反映我从你那里学到的东西。