我正在嘗試為 github 登錄頁面上的錯誤消息獲取 XPATH。( https://github.com/login )。但是我無法在 chrome 中獲取此元素的 XPATH我輸入了不正確的憑據并看到“不正確的用戶名或密碼”之后:我試圖通過 chrome 復制 XPATH$x("//*[@id='js-flash-container']/div/div/text()")但它返回 (2) [text, text]$x("//div[contains(text(), 'Incorrect username or password.')]")但它什么也沒返回HTML:<div class="flash flash-full flash-error"> <div class="container"> <button class="flash-close js-flash-close" type="button" aria-label="Dismiss this message"> <svg class="octicon octicon-x" viewBox="0 0 12 16" version="1.1" width="12" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"></path></svg> </button> Incorrect username or password. </div></div>我需要一條錯誤消息。但我沒有private By error = By.xpath("//*[@id='js-flash-container']/div/div/text()");
3 回答

慕蓋茨4494581
TA貢獻1850條經驗 獲得超11個贊
它更容易使用cssSelector
......
String error = driver.findElement(By.cssSelector("div .flash")).getText().trim(); System.out.println(error);
但是如果你想要 XPATH 使用:
String error = driver.findElement(By.xpath('//div[@class="container"]')).getText().trim(); System.out.println(error);

慕容森
TA貢獻1853條經驗 獲得超18個贊
提取錯誤消息不正確的用戶名或密碼。在 github 登錄頁面上,https://github.com/login
您需要為引入WebDriverWaitvisibilityOfElementLocated()
,您可以使用以下任一定位器策略:
cssSelector
:System.out.println(new?WebDriverWait(driver,?20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div#js-flash-container?div.container"))).getText());
xpath
:System.out.println(new?WebDriverWait(driver,?20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("http://div[@id='js-flash-container']//div[@class='container']"))).getText());

回首憶惘然
TA貢獻1847條經驗 獲得超11個贊
在 firefox 中,我找到了那個元素并發現 xpath 是:
/html/body/div[3]/main/div/form/div[2]/div/div
我加載了 firefox selenium 并通過 xpath 找到了這個元素:
WebElement error_msg = driver.findElement(By.xpath(ELEMENT_XPATH));
然后獲取我使用的文本:
文本 error_msg_str = error_msg.getText();
然后您可以將此字符串與“不正確的用戶名或密碼”進行比較。,如果這些匹配,則會引發錯誤。
添加回答
舉報
0/150
提交
取消