首页 > 解决方案 > 来自抓取迭代的 Python 嵌套列表不适合 Pandas 数据框

问题描述

我有这段代码,可以使用 Selenium 自动搜索数据库中的字符串,并使用 Beautifulsoup 抓取数据:

final_list = []
for x in short_list:
    search_query = driver.find_element_by_name('search_freetext')
    search_query.send_keys(x)
    time.sleep(2)
    search_query.send_keys(Keys.RETURN)
    time.sleep(2)
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    a = [x.get_text(strip=True) for x in soup.find_all('a',class_= 'title_link') if x.get_text().startswith(tuple(short_list))] 
    b = [x.get_text(strip=True) for x in soup.find_all('div',class_= 'dark_row regular_font')][0:len(a)]
    b = [' '.join(z.split()) for z in b]
    c = [list(pair) for pair in zip(a, b)]
    final_list.append(c)
    go_back = driver.find_element_by_xpath('//*[@id="results"]/div[1]/div[4]/div[1]/a[2]').click()
    time.sleep(2)

df = pd.DataFrame(final_list, columns = ['Company', 'Country'])

创建数据框时,df 返回错误,因为“final_list”有 20 列而不是给定的 2 列。

如果您打印“final_list”,则它是列表中的嵌套列表:

[[['comp1', 'countr1'], ['comp1', 'countr2']],[['comp2', 'countr2'], ['comp2', 'countr3']]]

发生这种情况是因为我将变量 c 附加到“final_list”。但是,如果我将“c”分配给数据框数据,它会正确填充数据框,但只有一个列表。

我的问题是如何正确附加来自 1 个循环的每个结果,即“c”变量?

或者如何解析列表中的嵌套列表以获取正确的数据库,如下所示:

Company Country
0   comp France  Cedex, Meuse, France
1   comp-Abello, Inc.   Round Rock, Texas, USA

标签: pythonpandasseleniumbeautifulsoupnested-lists

解决方案


使用extend()而不是append()这样你就不会嵌套列表

final_list.extend(c)

推荐阅读