如何从Selenium提供的HTML中提取动态文本3204255?

时间:2018-08-29 15:12:49

标签: javascript java selenium selenium-webdriver

我正在尝试从div中获取数字。执行测试用例时,将显示新的数字,现在我要获取该数字,或者换句话说,将其打印在控制台中。

我正在使用:

webElement webelement=driver.findElement(By.xpath("//div[contains(@class,'responsive now') and text()='Application number']"));
webelement.getText();

driver.findElement(By.xpath("//div[@class='responsive-show']")).getAttribute("value");

它与定位器无关,但没有显示数字。

<td> 
  <div class="responsive-show">Application number</div>
  "3204255" 
  <input data val="true" data-val-number="The field ExaminationNumber must be a number." data-val-required="The ExaminationNumber field is required." id="ActiveExamModeIs_0__ExaminationNumber" name="ActiveExamMode[0].ExaminationNumber" type="hidden" value="3204255"> 
  <input data -val="true" data-val-number="The field ExaminationEligibilityExamTypeId must be a number" data-val-required="The ExaminationEligibilityExamTypeId fiels is required." type="hidden" value="1">
</td>

enter image description here

3 个答案:

答案 0 :(得分:0)

文本:3204247不包含在div标签中,但包含在<td>中。 您可以尝试以下方法:

webElement webelement=driver.findElement(By.xpath("//table[@class='table table-hover']/tbody/tr/td"));// you can improve this locator and can also use one below
//webElement webelement=driver.findElement(By.xpath("//div[@class='responsive-show']/..")); using xpath axes
String value=webelement.getText();// OR
//String value=webelement.getAttribute("innerText");

答案 1 :(得分:0)

根据您共享的 HTML 提取数字,即 3204255 ,您需要诱使 WebDriverWait 为所需的元素可见,那么您可以按照以下解决方案使用executeScript()方法:

  • Java 解决方案:

    WebElement myElement = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table[@class='table table-hover']//tbody/tr/td")));
    String myText = ((JavascriptExecutor)driver).executeScript('return arguments[0].childNodes[2].textContent;', myElement).toString();
    

答案 2 :(得分:0)

长短:没有简单的方法使用简单的Selenium函数获取文本值,除非您要使用“ JavascriptExecutor”

另一种选择是使用简单的硒运算从content = html_response.content fixed_content = fromstring(content) # parse the HTML and correct malformed HTML items = fixed_content.xpath('//ul/li/*') 元素中获取整个文本,然后使用字符串函数items来获取您的申请号值,该值被放在引号li之间。

代码:

for item in items:
 text1 = item.xpath('/div[@id="div-1"]/div[@id="subdiv-1"]/a[@class="name"]/span').text_content()
 text2 = item.xpath('/div[@id="div-1"]/div[@id="subdiv-2"]/div[@class="class-1"]/div[@class="subClass-1"]/div').text_content()
 text3 = item.xpath('/div[@id="div-1"]/div[@id="subdiv-2"]/div[@class="class-1"]/div[@class="subClass-2"]/span[@class="subClass-2"]').text_content()