我正在嘗試將維基百科作為一個項目來學習一些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")]
添加回答
舉報
0/150
提交
取消