使用 Selenium 获取 Web 元素的 href 属性
Get href attribute of an element of a web using Selenium
我有这个,但是它 returns 网页的 url。我想要文本字符串中的“href”。
PATH_DATA = //[@id="vvp-product-details-modal--product-title"][@class="a-link-normal"]
WebElement myData = driver.findElement(By.xpath(PATH_DATA));
String url = myData.getAttribute("href")
是returns网页的url。我想要文本字符串中的“href”。
快照:
要打印 href
属性的值,您可以使用以下任一方法 :
使用 cssSelector:
System.out.println(wd.findElement(By.cssSelector("a.a-link-normal#vvp-product-details-modal--product-title")).getAttribute("href"));
使用 xpath:
System.out.println(wd.findElement(By.xpath("//a[@class='a-link-normal' and @id='vvp-product-details-modal--product-title']")).getAttribute("href"));
理想情况下,要提取 href
属性的值,您必须归纳 for the and you can use either of the following :
使用 cssSelector 和 getText()
:
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a.a-link-normal#vvp-product-details-modal--product-title"))).getAttribute("href"));
使用 xpath 和 getAttribute("innerHTML")
:
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='a-link-normal' and @id='vvp-product-details-modal--product-title']"))).getAttribute("href"));
像这样的东西是你最好的选择:
href = driver.execute_script("return document.querySelector('#vvp-product-details-modal--product-title')?.href")
我有这个,但是它 returns 网页的 url。我想要文本字符串中的“href”。
PATH_DATA = //[@id="vvp-product-details-modal--product-title"][@class="a-link-normal"]
WebElement myData = driver.findElement(By.xpath(PATH_DATA));
String url = myData.getAttribute("href")
是returns网页的url。我想要文本字符串中的“href”。
快照:
要打印 href
属性的值,您可以使用以下任一方法
使用 cssSelector:
System.out.println(wd.findElement(By.cssSelector("a.a-link-normal#vvp-product-details-modal--product-title")).getAttribute("href"));
使用 xpath:
System.out.println(wd.findElement(By.xpath("//a[@class='a-link-normal' and @id='vvp-product-details-modal--product-title']")).getAttribute("href"));
理想情况下,要提取 href
属性的值,您必须归纳
使用 cssSelector 和
getText()
:System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a.a-link-normal#vvp-product-details-modal--product-title"))).getAttribute("href"));
使用 xpath 和
getAttribute("innerHTML")
:System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='a-link-normal' and @id='vvp-product-details-modal--product-title']"))).getAttribute("href"));
像这样的东西是你最好的选择:
href = driver.execute_script("return document.querySelector('#vvp-product-details-modal--product-title')?.href")