Selenium难以在页面上找到输入元素(Python)

2024-09-29 00:20:33 发布

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

我有困难找到一个搜索栏上的网页,我试图自动化。我尝试过几种方法,但由于对selenium比较陌生,我不确定还有什么更高级的定位选项。在

故障: 下面是突出显示搜索栏元素(对应于输入)的代码部分

The xpath to the following highlighted section is below

//*[@id='core-content-container']/div/div[2]/div/div[1]/nav/div/div[2]/form/ul/li[1]/input

但是,当我试图通过xpath查找这个元素时,我得到了一个NoSuchElementException(我尝试过更短的xpath,但是那些路径提供了相同的错误)

下面是我用来查找此元素的相关代码位:

^{pr2}$

因为我要看的正是这条线:

<input type="text" class="form-control ng-pristine ng-untouched ng-valid" ng-model="query" placeholder="Full domain name">

然后我想也许我可以用

driver.find_element_by_css_selector('input.form-control.ng-pristine.ng-untouched.ng-valid')

由于这与第4.7节中有关seleniums python教程的示例相似,我认为这可以完成任务,但也不起作用(我得到另一个NoSuchElementException)。在


Tags: 方法代码divform元素网页inputselenium
1条回答
网友
1楼 · 发布于 2024-09-29 00:20:33

如果您将NoSuchElementException作为您提供的异常,可能有以下原因:

  • 可能是当您要查找元素时,DOM上不存在该元素,因此您应该使用WebDriverWait实现{a1},直到元素出现,如下所示:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div#core-content-container input.form-control[ng-model='query'][placeholder='Full domain name']")))
    
  • 可能是这个元素在任何frameiframe内。如果是,则需要在找到如下元素之前切换frame或{}:

     wait = WebDriverWait(driver, 10)
    
    #Find frame or iframe and switch
    wait.until(EC.frame_to_be_available_and_switch_to_it(("frame/iframe id or name")))
    
    #Now find the element 
    element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div#core-content-container input.form-control[ng-model='query'][placeholder='Full domain name']")))
    
    #Once all your stuff done with this frame need to switch back to default
    driver.switch_to_default_content()
    

相关问题 更多 >