硒找不到链接的元素

时间:2019-07-15 16:16:55

标签: python selenium selenium-webdriver

我正在尝试制作一个程序,该程序登录到我的depop(二手服装销售应用程序)中并搜索用户。到目前为止,我已经设法使其登录。但是,它找不到搜索按钮的元素。

我尝试了多种方法,但没有一种起作用。请记住,我今天已经开始学习此技巧,所以我是一个初学者。

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys #allows keyboard to be used
from selenium.webdriver.common.by import By #allow waiting
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as cond
from selenium.webdriver.support import expected_conditions as ec
from selenium.common.exceptions import NoAlertPresentException
from selenium.common.exceptions import TimeoutException

def search():
    driver.implicitly_wait(4)
    searchbox = driver.find_element_by_name('a')

消息:没有这样的元素:无法找到元素

根据我的处理方式,我只会得到此错误消息的变体。

编辑: 元素是:

a
< span > Search < /span >
/a

编辑2:在此按钮上添加更多详细信息以便于理解,当我单击该按钮时,它将使实际搜索栏变为下拉菜单。因此,如果最终找到了元素。它给了我这个“消息:陈旧元素引用:该元素未附加到页面文档”

2 个答案:

答案 0 :(得分:0)

a不是名称,因此不会导致使用方法find_element_by_name查找元素。请尝试使用xpath //span[text()='Search']查找元素搜索。请检查(在开发人员控制台或其他一些浏览器扩展程序中,如xpath,chropath等),使用此xpath返回了多少元素。如果只有一个要素,那您就走了。否则,在继续执行所需的操作之前,找到其他策略可以达到所需的元素。

答案 1 :(得分:0)

您的find_element_by_name function通过WebElement定位name attribute,在您的情况下,spana tag都没有name

因此您需要使用find_element_by_tag_name属性:

driver.find_element_by_tag_name("a")

,但是请注意,它将返回DOM的第一个链接,如果您需要将内部跨度与该链接匹配的文本与Search匹配,则需要像下面这样去XPath locator

driver.find_element_by_xpath("//span[contains(text(),'Search')]/parent::a")

将定位符包装到Explicit Wait

中也很好
相关问题