【问题标题】:Selenium - Unable to locate elementSelenium - 无法定位元素
【发布时间】:2021-06-21 03:21:32
【问题描述】:

我正在尝试使用 Selenium 从网站上抓取餐厅列表,但我总是收到错误 NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector ":".//*[@id="lista-encontrada"]/div[2]/div[1]/h4"}

我搜索过类似的错误,但它总是与 frame 或 iframe 有关,但我似乎无法在这个特定的网站上找到它们。代码如下:

from selenium import webdriver

url = 'https://www.restaurantemadero.com.br/pt/restaurante/sp/sao-paulo'

driver = webdriver.Chrome()
driver.get(url)
driver.maximize_window()

restaurants = driver.find_elements_by_class_name('blocos')

nome_loja = restaurants[0].find_element_by_xpath('.//*[@id="lista-encontrada"]/div[7]/div[1]/h4')

任何提示都会很有帮助!

【问题讨论】:

    标签: python selenium selenium-webdriver web-scraping xpath


    【解决方案1】:

    要获取restaurant name,请使用以下 xpath。 //div[@class='blocos']//h4

    以下代码将在列表中返回restaurant name

    使用文本的值:

    print([res.text for res in driver.find_elements_by_xpath("//div[@class='blocos']//h4")])
    

    或 使用 textContent:

    的值
    print([res.get_attribute("textContent") for res in driver.find_elements_by_xpath("//div[@class='blocos']//h4")])
    

    【讨论】:

    • 非常感谢昆都克!我仍在试图弄清楚你做了什么,但它奏效了!再次感谢!
    • 如果这解决了您的问题,请将此答案标记为已接受how to accept
    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 2017-11-27
    • 2018-07-06
    • 2020-07-05
    相关资源
    最近更新 更多