![](/img/trans.png)
[英]How to extract the text 121.6 from the text node within the span tag using Selenium and Python
[英]How to extract the text of a text node that is not inside a tag of its own using Selenium and Java?
我想得到一行文本(例如standard_user)。 我怎样才能做到这一点?
<div id="login_credentials" class="login_credentials">
<h4>Accepted usernames are:</h4>
standard_user
<br>
locked_out_user
<br>
problem_user
<br>
performance_glitch_user<br>
</div>
收集一个 div 中包含的所有文本,并用换行符将它们分开:
WebElement element = driver.findElement(By.id("login_credentials"));
String lines[] = element.getText().split("\n");
System.out.println(lines[1]);
您必须逐行读取文件并设置条件以获取没有标签的行
if(!line.startwith("<"){ //your code}
或使用库来读取 html 文件取决于您的编程语言
我会用几行来处理文本——使用<br>
元素和包含部分文本的元素有点棘手:
// first, get all the text by locating div element
string allText = driver.findElement(By.id("login_credentials")).getText();
// then get H4 text so we can remove this string
string textToRemove = driver.findElement(By.xpath("//div[@id='login_credentials']/h4")).getText();
// remove unwanted "Accepted usernames are:" text
string filteredText = allText.Replace(textToRemove, "");
// split filteredText on newline regex so we can get line items including 'standard_user'
string[] textArray = filteredText.split("\\r?\\n");
// get standard_user text by getting first item in the split array
string standardUserText = textArray[0];
这段代码的最后 3 行可以简化,但我写了这个更长的版本,这样我们就可以了解每一步发生了什么。
评估后的allText
变量应等于Accepted usernames are: standard_user locked_out_user problem_user performance_glitch_user
。
一旦我们删除了Accepted usernames are:
出现在h4
元素中的文本, filteredText
就等于standard_user locked_out_user problem_user performance_glitch_user
,每个项目用换行符分隔, \\r
或\\n
字符——我们使用正则表达式来处理这两种情况。 .
我们在\\n
字符上拆分filteredText
,因此我们得到一个数组,如下所示:
[ "standard_user", "locked_out_user", "problem_user", "performance_glitch_user" ]
然后,我们可以调用textArray[0]
来获取列表中的第一项,应该是standard_user
。
只需获取 div 内容并使用一些带换行符的字符串操作。
String text=driver.findElement(By.cssSelector("div#login_credentials")).getText();
String lines[] = text.split("\\r?\\n");
System.out.println(lines[1]);
文本standard_user是<div>
节点中的文本节点。 因此,要提取文本standard_user,您可以使用以下任一定位器策略:
使用cssSelector :
System.out.println((String)((JavascriptExecutor)driver).executeScript('return arguments[0].childNodes[2].textContent;', new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.login_credentials#login_credentials")))));
使用xpath :
System.out.println(((JavascriptExecutor)driver).executeScript('return arguments[0].childNodes[2].textContent;', new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='login_credentials' and @id='login_credentials']")))).toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.