[英]Get href attribute of an element of a web page using Selenium
I have this, but it returns the URL of the web page.我有这个,但它返回 web 页面的 URL。 I want the "href" in a text string.我想要文本字符串中的“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")
It returns the URL of the web page.它返回 web 页面的 URL。 I want the "href" in a text string.我想要文本字符串中的“href”。
Snapshot:快照:
To print the value of the href
attribute you can use either of the following locator strategies :要打印href
属性的值,您可以使用以下任一定位器策略:
Using cssSelector :使用cssSelector :
System.out.println(wd.findElement(By.cssSelector("aa-link-normal#vvp-product-details-modal--product-title")).getAttribute("href"));
Using xpath :使用xpath :
System.out.println(wd.findElement(By.xpath("//a[@class='a-link-normal' and @id='vvp-product-details-modal--product-title']")).getAttribute("href"));
Ideally, to extract the the value of the href
attribute, you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following locator strategies :理想情况下,要提取href
属性的值,您必须为visibilityOfElementLocated()引入WebDriverWait ,并且您可以使用以下任一定位器策略:
Using cssSelector and getText()
:使用cssSelector和getText()
:
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("aa-link-normal#vvp-product-details-modal--product-title"))).getAttribute("href"));
Using xpath and getAttribute("innerHTML")
:使用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"));
Something like this is your best bet:这样的事情是你最好的选择:
href = driver.execute_script("return document.querySelector('#vvp-product-details-modal--product-title')?.href")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.