簡體   English   中英

使用 Selenium 獲取 web 頁面元素的 href 屬性

[英]Get href attribute of an element of a web page using Selenium

我有這個,但它返回 web 頁面的 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")

它返回 web 頁面的 URL。 我想要文本字符串中的“href”。

快照:

在此處輸入圖像描述

要打印href屬性的值,您可以使用以下任一定位器策略

  • 使用cssSelector

     System.out.println(wd.findElement(By.cssSelector("aa-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屬性的值,您必須為visibilityOfElementLocated()引入WebDriverWait ,並且您可以使用以下任一定位器策略

  • 使用cssSelectorgetText()

     System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("aa-link-normal#vvp-product-details-modal--product-title"))).getAttribute("href"));
  • 使用xpathgetAttribute("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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM