首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Jupyter Notebook中使用BeautifulSoup抓取表

在Jupyter Notebook中使用BeautifulSoup抓取表
EN

Stack Overflow用户
提问于 2019-03-03 03:14:11
回答 2查看 843关注 0票数 1

我正在尝试用Beautifulsoup打印一张以列表格式给出的婴儿名字的表格。

google-python-exercises/google-python-exercises/babynames/baby1990.html (超文本标记语言页面是实际网址的屏幕截图)

在使用urllib.request获取表并使用BeautifulSoup解析它之后,我能够打印表的每一行中的数据,但是我得到了错误的输出。

下面是我的代码:

代码语言:javascript
运行
复制
right_table = soup.find('table',attrs = {"summary" : "Popularity for top 1000"})
table_rows = right_table.find_all('tr') 

for tr in table_rows:
td = tr.find_all('td')
row = [i.text for i in td]
print(row)

它应该打印一个包含行中所有数据的列表,但是,我得到了许多列表,每个新列表的开头都少了一条记录

有点像这样:

代码语言:javascript
运行
复制
['997', 'Eliezer', 'Asha', '998', 'Jory', 'Jada', '999', 'Misael', 'Leila', '1000', 'Tate', 'Peggy', 'Note: Rank 1 is the most popular,\nrank 2 is the next most popular, and so forth. \n']
['998', 'Jory', 'Jada', '999', 'Misael', 'Leila', '1000', 'Tate', 'Peggy', 'Note: Rank 1 is the most popular,\nrank 2 is the next most popular, and so forth. \n']
['999', 'Misael', 'Leila', '1000', 'Tate', 'Peggy', 'Note: Rank 1 is the most popular,\nrank 2 is the next most popular, and so forth. \n']
['1000', 'Tate', 'Peggy', 'Note: Rank 1 is the most popular,\nrank 2 is the next most popular, and so forth. \n']
['Note: Rank 1 is the most popular,\nrank 2 is the next most popular, and so forth. \n']

如何只打印一个列表?

EN

回答 2

Stack Overflow用户

发布于 2019-03-03 03:25:08

我将尝试使用pandas和索引到表的结果列表中,以获得您想要的表

代码语言:javascript
运行
复制
import pandas as pd

tables = pd.read_html('yourURL')

print(tables[1]) # for example; change index as required
票数 2
EN

Stack Overflow用户

发布于 2019-03-03 03:20:53

你的循环正在创建你的行列表,然后打印它,然后进入下一次迭代,在那里它创建一个行列表(覆盖之前的列表),然后打印它,等等。

不知道为什么要将所有行都放到一个列表中,但是为了拥有一个最终列表,您需要在每次迭代时将每个行列表附加到一个最终列表中。

您的实际意思是想要一个行列表列表吗?

代码语言:javascript
运行
复制
right_table = soup.find('table',attrs = {"summary" : "Popularity for top 1000"})
table_rows = right_table.find_all('tr') 


result_list = []
for tr in table_rows:
    td = tr.find_all('td')
    row = [i.text for i in td]
    result_list = result_list + row


print(result_list)

如果您真的想要一个行的列表,那么使用下面的列表:

代码语言:javascript
运行
复制
right_table = soup.find('table',attrs = {"summary" : "Popularity for top 1000"})
table_rows = right_table.find_all('tr') 


result_list = []
for tr in table_rows:
    td = tr.find_all('td')
    row = [i.text for i in td]
    result_list.append(row)


print(result_list)

但老实说,我会按照QHarr的建议使用pandas和.read_html()。

代码语言:javascript
运行
复制
right_table = soup.find('table',attrs = {"summary" : "Popularity for top 1000"})
table_rows = right_table.find_all('tr') 


result_list = []
for tr in table_rows:
    td = tr.find_all('td')
    for data in td:
        print (td.text)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54962107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档