首页 > 解决方案 > 试图在 div 中抓取 div 中的元素,但无法弄清楚

问题描述

我正在尝试使用 python 从网站上抓取餐馆的名称。我很难弄清楚要定位哪个确切的 div 类,然后如何编写代码来进行抓取。我已经成功地为其他网页编写了代码,但无法弄清楚这个。

我的目标是这个网页:https ://www.broadsheet.com.au/melbourne/fitzroy

这是我尝试过的:

soup_rest_list = BeautifulSoup(html_rest, 'html.parser')
type(soup_rest_list)

rest_container = soup_rest_list.find_all(class_="venue-teaser-list format-horizontal VenueTeaserListWrapper-sc-13dcca9-1 fIcGQi", "h2", class_="venue-title")

虽然我没有得到太多的爱。现在当我执行我的代码时,我只得到一个 []

非常感谢任何帮助。

标签: pythonweb-scrapingbeautifulsoup

解决方案


使用find_all,您只需h2在 class中查找标签venue-title,然后提取其text属性。

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup

options = webdriver.ChromeOptions()
options.add_argument('--no-sandbox')
options.add_argument('--disable-gpu')

driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)


url = 'https://www.broadsheet.com.au/melbourne/fitzroy'
driver.get(url)

page = BeautifulSoup(driver.page_source, 'html')
elements = page.find_all("h2", class_="venue-title")
names = [i.text for i in elements]

>> names
 
['Poodle Bar & Bistro',
 'Gogyo',
 'Rice Queen',
 'Vegie Bar',
 'Smith & Daughters',
 'Belles Hot Chicken Fitzroy',
 'Grub Fitzroy',
 'Archie’s All Day',
 'Sonido',
 'Gabriel',
 'Mile End Bagels',
 'Napier Quarter',
 'Bonny',
 'Near & Far',
 'The Everleigh',
 "Milney's",
 'Mono-XO',
 'The Rum Diary Bar',
 'Smith & Deli',
 'Meatsmith Fitzroy',
 'American Vintage',
 'Hunter Gatherer',
 'Plane',
 'Aesop']

推荐阅读