python - 来自抓取迭代的 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
解决方案
使用extend()
而不是append()
这样你就不会嵌套列表
final_list.extend(c)
推荐阅读
- function - 从 Julia 的包中复制函数
- google-chrome - 我会在 Chrome Bug Bounty 上提交这个 bug 获得奖励吗?
- php - Codeigniter - 插入多个表
- javascript - 为什么 selection.exit().size() 为零?
- amazon-web-services - 如何将用户制作的脚本添加到 EC2 ubuntu?
- c# - 如何根据 Web API 2 ASP.NET 中收到的操作做出响应
- c# - Unity 在多个游戏对象上更改材质颜色
- android - 如何对具有泛型类型的 kotlin 扩展函数进行单元测试
- javascript - 使用逻辑运算符解构状态分配
- java - 无法弄清楚如何检测硬币翻转器中有多少连续的正面