使用beautifulsoup从页面中删除特定的机场代码

2024-10-01 19:20:47 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的第一个职位,请随时让我知道我可以更好地张贴,并提前感谢您的帮助。你知道吗

我正在学习如何用python使用BeautifulSoup从网页中抓取数据,并且很难抓取loungebuddy运行的所有机场。你知道吗

import requests
from bs4 import BeautifulSoup

page = requests.get('https://www.loungebuddy.com/select/locations')
soup = BeautifulSoup(page.text, 'html.parser')
airport_code_html_lines = soup.find_all( attrs={'class': 'aiprt-code'})

这让我非常接近,但我有无关的数据。我想要的结果是以下提供的每个结果的第二行:

    for airport_code in airport_code_html_lines:
        print(airport_code.prettify())

我想把这个非常简单的案例个人化:

https://medium.freecodecamp.org/how-to-scrape-websites-with-python-and-beautifulsoup-5946935d93fe

作者从中提取价格部分。但是,当我尝试

price = price_box.text

我得到这个错误:

AttributeError: ResultSet object has no attribute 'txt'. You're probably 
treating a list of items like a single item. Did you call find_all() when you 
meant to call find()?

Python猜对了,我正在使用find all…但是我不知道如何继续。你知道吗

我试过使用不同的打印功能,比如

print(airport_code.strip('>'))

看看是否可以通过创建新变量或使用创造性的打印命令来剥离或隔离代码,但我得到了以下结果:

TypeError: 'NoneType' object is not callable

我很喜欢下一步尝试的任何一个方向(考虑将find\u all更改为find,然后创建for循环…,但这对我来说很吓人。希望有一个更干净的解决方案),或工作代码,将吐出我想要的结果。我希望通过这个项目和将来都能学习python,所以对我的思想过程的任何评论都表示感谢。你知道吗

再次感谢


Tags: 数据texthttpsimporthtmlpagecodeall
2条回答

如果你想知道机场代码和国家名称,你可以试试下面的方法:

import requests
from bs4 import BeautifulSoup

page = requests.get('https://www.loungebuddy.com/select/locations')
soup = BeautifulSoup(page.text, 'html.parser')
airport_code = {item.select_one("h2").text:item.select_one(".aiprt-code").text for item in soup.select(".country")}
print(airport_code)

部分输出:

{'India': 'BLR', 'Poland': 'KTW', 'Thailand': 'BKK', 'Croatia': 'ZAG', so on }

只需将print(airport_code.prettify())替换为print(airport_code.text)即可得到所需的输出。你知道吗

请尝试以下代码(使其更干净):

page = requests.get('https://www.loungebuddy.com/select/locations')
soup = BeautifulSoup(page.text, 'html.parser')

for country in soup.find_all('span', class_='aiprt-code'):
    print(country.text)

你也可以用soup.find_all('span', {'class': 'aiprt-code'})代替soup.find_all('span', class_='aiprt-code')。是一样的。你知道吗

输出:

BNE
SYD
BGI
BRU
...
...

或者,如果您想在列表中列出国家,您可以使用list comprehension,如下所示。它有助于存储、使用和修改数据。你知道吗

countries = [x.text for x in soup.find_all('span', class_='aiprt-code')]
print(countries)

输出:

['BNE', 'SYD', 'BGI', 'BRU', 'GIG', 'SOF', 'PNH', 'REP', ... ]

相关问题 更多 >

    热门问题