在python中将一系列字符串转换为列表



我正试图将维基百科作为一个项目来学习一些python 3。我已经设法从一个页面获得了链接:

import urllib.request
from bs4 import BeautifulSoup    
html_code = urllib.request.urlopen('https://en.wikipedia.org/wiki/Category:Lists_of_airports_by_country').read().decode()
souped_code = BeautifulSoup(html_code, "html.parser")
for element in souped_code.find_all("a"):
dest_links = element.get('href')
print(dest_links)

但我只是得到了一系列我想使用的字符串(比如在列表中,这样就可以使用索引,只保留"list_of_airports_in_"链接(,并对它们进行过滤、打开、迭代等,但我只是无法理解如何实现这一点,因为它似乎会产生一系列字符串。

任何见解都将不胜感激!

您需要定义一个空列表并向其添加链接:

links = []
for element in souped_code.find_all("a"):
links.append(element.get('href'))
print(links)

或者使用列表理解:

links = [element.get('href') for element in souped_code.find_all("a")]

最新更新