无法使用Python在Selenium中定位元素?

2024-09-29 23:15:11 发布

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

以下是网站链接:

https://www.milanuncios.com/anuncios/?fromSearch=1&fromSuggester=0&suggestionUsed=0

单击名为Llamar的按钮以查看div

我一直在努力获取div的文本

为此,我必须找到这个div元素

这是div元素在浏览器中的外观:

enter image description here

Html代码

<div class="telefonos">699771517</div>

我尝试了两行python代码:

Python代码

TeleFonos = driver.find_element_by_class_name("telefonos")
print(TeleFonos.text)

但我总是犯这样的错误

错误

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".telefonos"}

你知道我做错了什么吗


Tags: 代码httpsdivcom元素网站链接www
2条回答

是否在Selenium查看页面时未加载元素

我建议看看这里关于使用Selenium的建议

https://stackoverflow.com/a/27112797/4352317

如果有问题的网站是共享的,这可能有助于对问题进行分类

元素位于iframe中,因此需要切换到该iframe中,然后进行搜索。为此,请使用以下代码-

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 60)
driver.get('https://www.milanuncios.com/anuncios/?fromSearch=1&fromSuggester=0&suggestionUsed=0')

wait.until(EC.presence_of_element_located((By.XPATH, "//button[@data-testid=\"TcfAccept\"]"))).click()

try:
    All_Phone = wait.until(
        EC.visibility_of_all_elements_located((By.XPATH, "//a[contains(@onclick,\"phoneContactFromAdList\")]")))
    for phone in All_Phone:
        phone.click()
        iframe = wait.until(EC.presence_of_element_located((By.ID, "ifrw")))
        driver.switch_to.frame(iframe)
        print(wait.until(EC.presence_of_element_located((By.CLASS_NAME, "telefonos"))).text)
        driver.switch_to.default_content()
        driver.find_element_by_xpath("//a[contains(text(),\"Cerrar\")]").click()
except:
    pass

如果它解决了您的问题,请将其标记为答案

相关问题 更多 >

    热门问题