使用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]")

猜你喜欢

转载自blog.csdn.net/xyq54/article/details/84060739