python - Selenium - 无法定位元素
问题描述
我正在尝试使用 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')
任何提示都会非常有帮助!
解决方案
要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的 OR 值:
print([res.get_attribute("textContent") for res in driver.find_elements_by_xpath("//div[@class='blocos']//h4")])
推荐阅读
- django - 实现用户注册和登录最常用的方式是什么?
- conv-neural-network - 在detectron2 的训练过程中,输入图像的大小是否调整为固定的宽度和高度?
- javascript - 如何在调整大小后立即更新添加的 fabric.js 形状?
- python - 以百分比计算 df 的频率
- javascript - 如何在 Laravel / livewire / alpinejs 应用程序中使用 pikaday?
- migration - 获取QueryFailedError:SQLITE_ERROR:没有这样的表:在测试环境中使用带有typeorm迁移的nestjs时的用户
- css - 如何使小屏幕上的导航栏在 Firefox 浏览器上兼容?
- android - 如何在按钮单击上打开 datePicker?在喷气背包组成
- python - 如何在数据透视后对python中数据框中的索引列以外的列进行排序
- django - 在没有视图的情况下使用 django hitcount 模块