[英]Unable to click a href link using Selenium
我有一個HTML href鏈接
<a class="btn btn-icon-text btn-secondary" data-toggle="modal" data-target="#recordSharingDownloadModal" href="/person/mL7CD8tR59g2Cy2/health-record/sharing/media/clinical-summary/%7B7c-06-74-be-dc-67-47-5d-be-92-4c-58-5a-fd-1b-8f%7D/download-options/" title="Download Document">Download</a>
使用硒,我需要單擊鏈接。 目前,我正在使用以下代碼-
driver.findElement(By.xpath("//a[contains(@href='/person/mL7CD8tR59g2Cy2/health-record/sharing/media/clinical-summary/%7B7c-06-74-be-dc-67-47-5d-be-92-4c-58-5a-fd-1b-8f%7D/download-options/')]")).click();
但是它拋出一個錯誤
“ java.lang.NullPointerException”
我也嘗試過使用CssSelector單擊按鈕,但仍然是相同的錯誤。 我需要單擊“臨床摘要”部分下的“下載”按鈕,但是有多個具有相同按鈕名稱的部分。 只有HREF是唯一的。
誰能幫幫我嗎?
這段代碼:
package LaunchIQHealth;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.*;
public class AutomateIQHealth
{
public static void main(String[] args) throws IOException, InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\abc\\Desktop\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 20);
driver.get("url");
((JavascriptExecutor)driver).executeScript("scroll(0,400)").equals("Clinical Summaries");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(), 'Download")));
driver.findElements(By.xpath("//a[@href='/person/mL7CD8tR59g2Cy2/health-record/sharing/media/clinical-summary/%7B7c-06-74-be-dc-67-47-5d-be-92-4c-58-5a-fd-1b-8f%7D/download-options/']")).get(0).click();
}
}
如果我認為您當前粘貼的代碼是正確的代碼,則您將無法執行以下任一操作:
driver.findElement(By.xpath("//a[contains(@href='/person/mL7CD8tR59g2Cy2/health-record/sharing/media/clinical-summary/%7B7c-06-74-be-dc-67-47-5d-be-92-4c-58-5a-fd-1b-8f%7D/download-options/')]")).click();
要么
driver.findElements(By.xpath("//a[@href='/person/mL7CD8tR59g2Cy2/health-record/sharing/media/clinical-summary/%7B7c-06-74-be-dc-67-47-5d-be-92-4c-58-5a-fd-1b-8f%7D/download-options/']")).get(0).click();
原因是, chromedriver
高興為您打開Chrome Browser
,但是您嘗試執行executeScript("scroll(0,400)").equals("Clinical Summaries");
但是根據文檔 JavascriptExecutor
它是一個Interface
以及關聯的方法executeScript
和executeAsyncScript
不能調用click()
方法。
您是否嘗試過給anchor
一個id
並使用findElement(By.id(IDTag))
?
我使用的替代方法是元素上的sendKeys(ENTER)
。
一個或另一個通常有效。
怎么樣,
WebElement element = driver.findElement(By.xpath("//*[@data-target='#recordSharingDownloadModal']")
System.out.println(element)
element.click();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.