我正在尝试用Beautifulsoup打印一张以列表格式给出的婴儿名字的表格。
google-python-exercises/google-python-exercises/babynames/baby1990.html (超文本标记语言页面是实际网址的屏幕截图)
在使用urllib.request获取表并使用BeautifulSoup解析它之后,我能够打印表的每一行中的数据,但是我得到了错误的输出。
下面是我的代码:
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)
它应该打印一个包含行中所有数据的列表,但是,我得到了许多列表,每个新列表的开头都少了一条记录
有点像这样:
['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']
如何只打印一个列表?
发布于 2019-03-03 03:25:08
我将尝试使用pandas和索引到表的结果列表中,以获得您想要的表
import pandas as pd
tables = pd.read_html('yourURL')
print(tables[1]) # for example; change index as required
发布于 2019-03-03 03:20:53
你的循环正在创建你的行列表,然后打印它,然后进入下一次迭代,在那里它创建一个行列表(覆盖之前的列表),然后打印它,等等。
不知道为什么要将所有行都放到一个列表中,但是为了拥有一个最终列表,您需要在每次迭代时将每个行列表附加到一个最终列表中。
您的实际意思是想要一个行列表列表吗?
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)
如果您真的想要一个行的列表,那么使用下面的列表:
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()。
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)
https://stackoverflow.com/questions/54962107
复制相似问题