Python 来自抓取迭代的嵌套列表不适合 Pandas 数据框
Python nested list from scraping iteration not suitable to Pandas dataframe
我有这段代码可以使用 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 returns 出错,因为 '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
使用 extend()
而不是 append()
,这样您就不会嵌套列表
final_list.extend(c)
我有这段代码可以使用 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 returns 出错,因为 '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
使用 extend()
而不是 append()
,这样您就不会嵌套列表
final_list.extend(c)