webdriver的元素定位很灵活,提供了多种定位方式:
Id
LinkText
PartialLinkText
Name
TagName
Xpath
ClassName
CssSelector
这些方法可以在org.openqa.selenium.By中找到,下面一一道来;
假如有这样的需求:登录安居客网站,搜索陆家嘴附近的二手房源,网页是这样的
这个需求涉及到一个输入框和一个提交按钮,先查看网页源码
在输入框中输入“陆家嘴”然后点击“二手房”按钮,如果能跳转到陆家嘴相关页面就完成了这个需求,我们尝试用webdriver提供的元素定位方法来解决
Id
id是唯一标识,通过id来定位是非常快速和准确的
import org.openqa.selenium.By;import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; public class NewTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://anjuke.com"); //id WebElement text=driver.findElement(By.id("glb_search0")); text.sendKeys("陆家嘴"); WebElement button=driver.findElement(By.id("btnSubmit")); button.click(); if(driver.getTitle().contains("陆家嘴")) System.out.print("搜索成功,当前页面为"+driver.getTitle()); else System.out.print("搜索失败,当前页面为"+driver.getTitle()); driver.quit(); } }
Name
提交表单时可以通过name属性获取数据,较id来说并不常用,有id属性时建议优先使用id属性,上面的源码中text输入框是有name属性的,button依然用id来获取(当然,如果测试需要的话可以修改源码,没有修改源码权限的自动化测试是很难进行的)。
import org.openqa.selenium.By;import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; public class NewTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://anjuke.com"); //name WebElement text=driver.findElement(By.name("kw")); text.sendKeys("陆家嘴"); WebElement button=driver.findElement(By.id("btnSubmit")); button.click(); if(driver.getTitle().contains("陆家嘴")) System.out.print("搜索成功,当前页面为"+driver.getTitle()); else System.out.print("搜索失败,当前页面为"+driver.getTitle()); driver.quit(); } }
TagName
tagname一般用来获取批量数据,如统计页面链接数,输入框数量等等,用tagname来定位单一元素有点麻烦
import java.util.List;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; public class NewTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://anjuke.com"); List<WebElement> inputs=driver.findElements(By.tagName("input")); for(int index=0;index<inputs.size();index++){ if(inputs.get(index).getAttribute("id").equals("glb_search0")) inputs.get(index).sendKeys("陆家嘴"); if(inputs.get(index).getAttribute("id").equals("btnSubmit")) inputs.get(index).click(); } if(driver.getTitle().contains("陆家嘴")) System.out.print("搜索成功,当前页面为"+driver.getTitle()); else System.out.print("搜索失败,当前页面为"+driver.getTitle()); driver.quit(); } }
ClassName
当标签具有class属性时也可使用classname来定位,不过要注意class的值不是唯一的findElement方法返回匹配到的第一个元素
import org.openqa.selenium.By;import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; public class NewTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://anjuke.com"); //classname WebElement text=driver.findElement(By.className("kw")); text.sendKeys("陆家嘴"); WebElement button=driver.findElement(By.className("btn")); button.click(); if(driver.getTitle().contains("陆家嘴")) System.out.print("搜索成功,当前页面为"+driver.getTitle()); else System.out.print("搜索失败,当前页面为"+driver.getTitle()); driver.quit(); } }
Xpath
xpath相关教程可以参考w3school上的教程,为了程序的统一性,平时工作中我都是使用xpath来定位元素的
import org.openqa.selenium.By;import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; public class NewTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://anjuke.com"); //xpath WebElement text=driver.findElement(By.xpath("//input[@id='glb_search0']")); text.sendKeys("陆家嘴"); WebElement button=driver.findElement(By.xpath("//input[@id='btnSubmit']")); button.click(); if(driver.getTitle().contains("陆家嘴")) System.out.print("搜索成功,当前页面为"+driver.getTitle()); else System.out.print("搜索失败,当前页面为"+driver.getTitle()); driver.quit(); } }
CssSelector
CssSelector教程可以参考css3-selectors,CssSelector和xpath应该是实际工作中用的最多的定位方法了,两者没有优劣之分,看个人喜好吧。
import org.openqa.selenium.By;import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; public class NewTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://anjuke.com"); //cssSelector WebElement text=driver.findElement(By.cssSelector("input[id='glb_search0']")); text.sendKeys("陆家嘴"); WebElement button=driver.findElement(By.cssSelector("input[id='btnSubmit']")); button.click(); if(driver.getTitle().contains("陆家嘴")) System.out.print("搜索成功,当前页面为"+driver.getTitle()); else System.out.print("搜索失败,当前页面为"+driver.getTitle()); driver.quit(); } }
LinkText和PartialLinkText
LinkText和PartialLinkText用来定位网页中的超链接,需要a标签中的全部或部分内容即可。例如,需要访问热门版块中的古美罗阳可以这样定位
import org.openqa.selenium.By;import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; public class NewTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://anjuke.com"); //linkText WebElement a=driver.findElement(By.linkText("古美罗阳")); a.click(); //partialLinkText //WebElement a=driver.findElement(By.partialLinkText("古美")); //a.click(); if(driver.getTitle().contains("古美罗阳")) System.out.print("访问成功,当前页面为"+driver.getTitle()); else System.out.print("访问失败,当前页面为"+driver.getTitle()); driver.quit(); } }
层级定位
webdriver提供了层级定位的方式即通过父元素访问其子元素,比如,输出热门版块下的所有版块
import java.util.List;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; public class NewTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://anjuke.com"); WebElement element=driver.findElement(By.xpath("//div[@id='content_Rd0']/dl[@class='dl0']/dd")); List<WebElement> links=element.findElements(By.tagName("a")); for(int index=0;index<links.size();index++){ System.out.println(links.get(index).getAttribute("text")); } driver.quit(); } }

Htmlisnotaprogramminglanguage; itisamarkuplanguage.1) htmlstructuresandformatswebcontentusingtags.2) itworksporstylingandjavaScriptOfforIncincivity, WebDevelopment 향상.

HTML은 웹 페이지 구조를 구축하는 초석입니다. 1. HTML은 컨텐츠 구조와 의미론 및 사용 등을 정의합니다. 태그. 2. SEO 효과를 향상시키기 위해 시맨틱 마커 등을 제공합니다. 3. 태그를 통한 사용자 상호 작용을 실현하려면 형식 검증에주의를 기울이십시오. 4. 자바 스크립트와 결합하여 동적 효과를 달성하기 위해 고급 요소를 사용하십시오. 5. 일반적인 오류에는 탈수 된 레이블과 인용되지 않은 속성 값이 포함되며 검증 도구가 필요합니다. 6. 최적화 전략에는 HTTP 요청 감소, HTML 압축, 시맨틱 태그 사용 등이 포함됩니다.

HTML은 웹 페이지를 작성하는 데 사용되는 언어로, 태그 및 속성을 통해 웹 페이지 구조 및 컨텐츠를 정의합니다. 1) HTML과 같은 태그를 통해 문서 구조를 구성합니다. 2) 브라우저는 HTML을 구문 분석하여 DOM을 빌드하고 웹 페이지를 렌더링합니다. 3) 멀티미디어 기능을 향상시키는 HTML5의 새로운 기능. 4) 일반적인 오류에는 탈수 된 레이블과 인용되지 않은 속성 값이 포함됩니다. 5) 최적화 제안에는 시맨틱 태그 사용 및 파일 크기 감소가 포함됩니다.

WebDevelopmentReliesonHtml, CSS 및 JavaScript : 1) HtmlStructuresContent, 2) CSSSTYLESIT, 및 3) JAVASCRIPTADDSINGINTERACTIVITY, BASISOFMODERNWEBEXPERIENCES를 형성합니다.

HTML의 역할은 태그 및 속성을 통해 웹 페이지의 구조와 내용을 정의하는 것입니다. 1. HTML은 읽기 쉽고 이해하기 쉽게하는 태그를 통해 컨텐츠를 구성합니다. 2. 접근성 및 SEO와 같은 시맨틱 태그 등을 사용하십시오. 3. HTML 코드를 최적화하면 웹 페이지로드 속도 및 사용자 경험이 향상 될 수 있습니다.

"Code"는 "Code"BroadlyIncludeLugageslikeJavaScriptandPyThonforFunctureS (htMlisAspecificTypeofCodeFocudecturecturingWebContent)

HTML, CSS 및 JavaScript는 웹 개발의 세 가지 기둥입니다. 1. HTML은 웹 페이지 구조를 정의하고 등과 같은 태그를 사용합니다. 2. CSS는 색상, 글꼴 크기 등과 같은 선택기 및 속성을 사용하여 웹 페이지 스타일을 제어합니다.

HTML은 웹 구조를 정의하고 CSS는 스타일과 레이아웃을 담당하며 JavaScript는 동적 상호 작용을 제공합니다. 세 사람은 웹 개발에서 의무를 수행하고 화려한 웹 사이트를 공동으로 구축합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

드림위버 CS6
시각적 웹 개발 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.
