selenium操作隐藏的元素

上一篇 / 下一篇  2016-11-18 14:12:46 / 个人分类:Selenium

 有时候我们会碰到一些元素不可见,这个时候selenium就无法对这些元素进行操作了。例如,下面的情况:51Testing软件测试网5C*Ss|K'FuR|mGqB

Bo%Y/e8?+A&Q*^Q051Testing软件测试网zU"jgK

 

R0q `H _%HG\0

Python                                                     

~7O0YL)SV Fx Z F0  页面主要通过“display:none”来控制整个下拉框不可见。这个时候如果直接操作这个下拉框,就会提示:

s6ZN~9L s f-Z0
复制代码
fromseleniumimportwebdriverfromselenium.webdriver.support.selectimportSelectimportos,time

driver=webdriver.Chrome()
file_path='file:///'+ os.path.abspath('test.html')
driver.get(file_path)

sel= driver.find_element_by_tag_name('select')
Select(sel).select_by_value('opel')
time.sleep(2)

driver.quit()
复制代码
51Testing软件测试网F U-YYAA

  exceptions.ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated

)m6D0Yh$l(e5\~Qg$f051Testing软件测试网9i7i:yqo:[%y$w

 

1v n:q/u;V(M"y:d Q\051Testing软件测试网l u.r$^O O e^;KH

  我们需要通过javaScript修改display的值。

({/a7K#[yty5CR0
复制代码
……

js='document.querySelectorAll("select")[0].style.display="block";'driver.execute_script(js)

sel= driver.find_element_by_tag_name('select')
Select(sel).select_by_value('opel')

……
复制代码

2Z L|*F l0document.querySelectorAll("select")[0].style.display="block";51Testing软件测试网,_ RqA0j_:L&K

51Testing软件测试网8C,Jh8ax)?*I*j

  document.querySelectorAll("select")  选择所有的select

!xhf&{f5Y051Testing软件测试网bh+T'}:WU

  [0] 指定这一组标签里的第几个。51Testing软件测试网/j-Q*b7wd!Q.J%rk

pfv7NQ)tF0  style.display="block";  修改样式的display="block" ,表示可见。

7Pw)QrqiO]0

t fKNd^F)Zy*{$TQ0  执行完这句js代码后,就可以正常操作下拉框了。

up1JP.s1Q;St*s0

} P%|)u3mW&T f;F0 51Testing软件测试网4kHR8Bn

Java                                                         

%n}(t!P3v*T2[I df9Pn0   以下为java中的操作51Testing软件测试网0~3j C'HO c

复制代码
packagecom.jase.base;importjava.io.File;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.By.ById;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.support.ui.Select;importorg.openqa.selenium.JavascriptExecutor;publicclassSelectTest {publicstaticvoidmain(String[] args){
        
        WebDriver driver=newChromeDriver();File file =newFile("C:/Users/fnngj/Desktop/test.html");
        String filePath=file.getAbsolutePath();
        driver.get(filePath);
        
         String js="document.querySelectorAll('select')[0].style.display='block';";
        ((JavascriptExecutor)driver).executeScript(js);
        
        Select sel=newSelect(driver.findElement(ById.xpath("//select")));
        sel.selectByValue("opel");
  
    }
}
复制代码

TAG: 元素

 

评分:0

我来说两句

Open Toolbar