为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

侃侃无极 2023-09-12 16:49:40
我正在尝试将维基百科作为一个项目来学习一些Python 3。我已经设法从页面获取链接:import urllib.requestfrom 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_”链接)并对它们进行过滤、打开、迭代等,但我只能我不知道如何实现这一点,因为它似乎会产生一系列字符串。任何见解将不胜感激!
查看完整描述

1 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

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


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")]


查看完整回答
反对 回复 2023-09-12
  • 1 回答
  • 0 关注
  • 66 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信