How to get text of an element on the basis of other element's text value on the same row in the table?

纵饮孤独 提交于 2020-01-30 08:12:28

问题


I need to find the text of an element "score" on the basis of other element "SF Lead ID" on the same row.

"SF Lead ID" can be dynamic. for example am using hard coded value here.

String sf_id = "00Q1l000003clVhEAI"; //this value is dynamic
String text= dvr.findElement(By.xpath("//*/tr/[contains(text(),'" + sf_id + "')]//*[@id='lead-score']")).getText();

Please look the html structure on the above image. help me to correct the xpath.

Currently its throwing below error -

org.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression //*/tr/[contains(text(),'00Q1l000003cldHEAQ')]//*[@id='lead-score'] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//*/tr/[contains(text(),'00Q1l000003cldHEAQ')]//*[@id='lead-score']' is not a valid XPath expression.
  (Session info: chrome=76.0.3809.132)
  (Driver info: chromedriver=2.38.552518 (183d19265345f54ce39cbb94cf81ba5f15905011),platform=Mac OS X 10.12.6 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/invalid_selector_exception.html

回答1:


To extract the score with respect to SF Lead ID you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

  • Using cssSelector and getText():

    String sf_id = "00Q1l000003clVhEAI";
    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("tr[data-sf-lead-id='" + sf_id + "'] td#lead-score"))).getText());
    
  • Using xpath and getAttribute():

    String sf_id = "00Q1l000003clVhEAI";
    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//tr[@data-sf-lead-id='" + sf_id + "']//td[@id='lead-score']"))).getAttribute("innerHTML"));
    


来源:https://stackoverflow.com/questions/57886216/how-to-get-text-of-an-element-on-the-basis-of-other-elements-text-value-on-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!