1. 程式人生 > >使用slenium+chromedriver定位網頁元素

使用slenium+chromedriver定位網頁元素

1、通過id來定位元素

<div id="coolestWidgetEvah">...</div>

java:

WebElement element = driver.findElement(By.id("coolestWidgetEvah"));

C#:

IWebElement element = driver.FindElement(By.Id("coolestWidgetEvah"));

python:

element = driver.find_element_by_id("coolestWidgetEvah")

2、通過class name來定位

<div class="cheese"><span>Cheddar</span></div><div class="cheese"><span>Gouda</span></div>

java:

List<WebElement> cheeses = driver.findElements(By.className("cheese"));

C#:

IList<IWebElement> cheeses = driver.FindElements(By.ClassName("cheese"));

python:

cheeses = driver.find_elements_by_class_name("cheese")

3、通過tag name

<iframe src="..."></iframe>

java:

WebElement frame = driver.findElement(By.tagName("iframe"));

C#:

IWebElement frame = driver.FindElement(By.TagName("iframe"));

python:

frame = driver.find_element_by_tag_name("iframe")

4、通過name

<input name="cheese" type="text"/>

java:

WebElement cheese = driver.findElement(By.name("cheese"));

C#:

IWebElement cheese = driver.FindElement(By.Name("cheese"));

python:

cheese = driver.find_element_by_name("cheese")

5、通過連結名稱

<a href="http://www.google.com/search?q=cheese">cheese</a>>

java:

WebElement cheese = driver.findElement(By.linkText("cheese"));

C#:

IWebElement cheese = driver.FindElement(By.LinkText("cheese"));

python:

cheese = driver.find_element_by_link_text("cheese")

6、通過部分連結名稱

<a href="http://www.google.com/search?q=cheese">search for cheese</a>>

java:

WebElement cheese = driver.findElement(By.partialLinkText("cheese"));

C#:

IWebElement cheese = driver.FindElement(By.PartialLinkText("cheese"));

python:

cheese = driver.find_element_by_partial_link_text("cheese")

7、通過CSS樣式

<div id="food"><span class="dairy">milk</span><span class="dairy aged">cheese</span></div>

java:

WebElement cheese = driver.findElement(By.cssSelector("#food span.dairy.aged"));

C#:

IWebElement cheese = driver.FindElement(By.CssSelector("#food span.dairy.aged"));

python:

cheese = driver.find_element_by_css_selector("#food span.dairy.aged")

8、通過xpath

<input type="text" name="example" />
<INPUT type="text" name="other" />

java:

List<WebElement> inputs = driver.findElements(By.xpath("//input"));

C#:

IList<IWebElement> inputs = driver.FindElements(By.XPath("//input"));

python:

inputs = driver.find_elements_by_xpath("//input")

9、通過javascript

java:

WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('.cheese')[0]");

C#:

IWebElement element = (IWebElement) ((IJavaScriptExecutor)driver).ExecuteScript("return $('.cheese')[0]");

python:
 

element = driver.execute_script("return $('.cheese')[0]")