xPath Text ประกอบด้วย Selenium Web Driver

Oct 27 2020

ฉันกำลังพยายามเลือกองค์ประกอบตามเนื้อหาข้อความ ฉันใช้ XPath เพื่อบรรลุสิ่งนี้

ฉันแค่งงว่ามันน่าจะใช้ได้ไหม

WebElement link = obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]")); 

ฉันจะคัดลอกโค้ด HTML:

<div class="linkWrap noCount">Notifications&nbsp;<span class="count _5wk0 hidden_elem uiSideNavCountText">(<span class="countValue fsm">0</span><span class="maxCountIndicator"></span>)</span></div>

องค์ประกอบ div มีคำว่า "การแจ้งเตือน" อยู่ข้างใน ทำไมมันไม่ทำงาน

ไปที่หน้านี้บน Facebook: https://www.facebook.com/settings

ใช้ส่วนขยาย chromeนี้เพื่อเน้นพื้นที่ใด ๆ ผ่าน xPath

คำตอบ

DMart Oct 27 2020 at 18:12

คุณมีช่องว่างก่อนคำว่า Notifications:

WebElement link = obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]"));    

คุณควรเพิ่มการรอองค์ประกอบก่อนที่จะพยายามค้นหาองค์ประกอบ:

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(), 'Notifications')]"));

WebElement link = obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]")); 
JackTrowbridge Oct 29 2020 at 20:21

ฉันพบปัญหาโดยได้รับความช่วยเหลือจากผู้คนที่น่าทึ่งบางคนในชุมชนนี้

โอเคองค์ประกอบของฉันอยู่ใน iFrame

ในการเข้าถึงองค์ประกอบฉันต้องเข้าถึง iFrame ก่อน

WebElement iframe = obj.driver.findElement(By.xpath("//iframe[@tabindex='-1']"));
    
obj.driver.switchTo().frame(iframe);