首页 > 解决方案 > 如何从段落中选择多个单词?(硒)

问题描述

网页由段落列表组成,当用户单击按钮时,应从该段落复制选定的单词。

如何通过 Selenium 实现这一点。?

我写了 javascript 代码,但它没有选择单词。

String script = "var range = document.createRange();" +
"var start = document.getElementsClassname('COTX1');" +
"var textNode = start.getElementsByTagName('p')[0].firstChild;" +
"range.setStart(textNode, 8);" +
"range.setEnd(textNode, 13);" +
"window.getSelection().addRange(range);";
 ((JavascriptExecutor)driver).executeScript(script);

例如在下面的段落中:我想选择从早到经济可行的词。

<p class="COTX1"><span class="CO_DC">A</span>s early as 1619, white Americans imported enslaved Africans to the New World with the idea of making agricultural enterprises such as tobacco growing more economically viable. Though most Americans considered it morally wrong, slavery persisted as part of the economic engine that European settlements built on these shores. The Founding Fathers knew that slavery violated the republic’s democratic principles, yet the constitutional debates of 1787–88 show that if it had been outlawed, some colonies would never have joined the union.</p>

标签: javascriptjavaselenium

解决方案


我认为,您可以使用 selenium 来获取完整的字符串并使用 regEx 来完成剩余的部分。

WebDriverWait wait = new WebDriverWait(driver, 10);
String entireString = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("p.COTX1"))).getText();
String[] strArray = entireString.split("\\.");
System.out.println(strArray[0]);

推荐阅读