有没有更好的方法来使用BeautifulSoup来刮取深埋在html文件中的数据?

2024-05-07 13:12:53 发布

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

我正在做一个个人项目,它会刮去我大学餐厅的菜单,并返回下一周的每日甜点菜单。我正在使用BeautifulSoup来实现这一点,但是我不确定我是否正确地使用了它,因为我的代码似乎是间接的和重复的。有没有一种方法可以不经过中间步骤直接跳到我的最后一行?以下是我目前的情况:

soup = bs.BeautifulSoup(sauce, 'lxml')
for column in soup.find_all('div', class_='menu-details-day'): # Looks at the menu for each day
    for station in column.find_all('div',class_='menu-details-station'): # Looks at each station
        if station.h4.string == 'Dessert' :
            for item in station.find_all('div',class_='menu-name'): # Looks at each item served at the dessert station
                # append items to list

为了澄清我的预期结果,我尝试在一天内得到每一种甜点,然后将其添加到对应于那一天的列表中。这是我正在刮的links之一。你知道吗


Tags: indivfor菜单allfindatclass
1条回答
网友
1楼 · 发布于 2024-05-07 13:12:53

如果因为不需要箭头代码而需要更好的方法,可以使用itertools将此逻辑转换为生成器管道

from itertools import chain

soup = bs.BeautifulSoup(sauce, 'lxml')

# extract all stations for each day
stations = chain(*(
    col.find_all('div',class_='menu-details-station') 
    for col in soup.find_all('div', class_='menu-details-day')
))
desserts = chain(*(
    station.find_all('div',class_='menu-name') 
    for station in stations
    if station.h4.string == 'Dessert'
))

for dessert in desserts:
    print(dessert)

相关问题 更多 >