我正在使用WebDriver在Java语言中编写程序,在执行select webElement后获取文本时遇到了一些问题。
我想要的网站部分的HTML代码如下:
<select name="language" id="langSelect" style="width:100px;">
<option value="1" >Français</option>
</select>
</div>
<div id="content">
<div id="Pagination"></div>
<div id="mid">
</div>
</div>
语言的搜索栏和下拉栏的textbox类代码
我的Java代码目前能够使用chrome驱动程序打开chrome,并且能够在搜索栏中输入内容。然而,我无法获得从该条目得到的文本。
在这里的图像中,我在搜索栏中输入了"avoir“,并且我希望框中的所有文本看起来都没有任何id或名称在xpath中使用。
有没有人可以帮我找到如何从这些字段中获取和保存下拉语言菜单后的文本?
提前谢谢你!
到目前为止,我的代码如下:
//import statements not shown
public class WebScraper {
public WebScraper() {
}
public WebDriver driver = new ChromeDriver();
public void openTestSite() {
driver.navigate().to(the URL for the website);
}
public void enter(String word) {
WebElement query_editbox =
driver.findElement(By.id("query"));
query_editbox.sendKeys(word);
query_editbox.sendKeys(Keys.RETURN);
}
public void getText() {
//List<WebElement> searchResults =
driver.findElements(By.xpath("//div[@id='mid']/div"));
// Writer writer = new BufferedWriter(new
OutputStreamWriter(new FileOutputStream("status.txt"),
"utf-8"));
//int[] index = {0};
WebElement result=driver.findElement(By.id("mid"));
System.out.println(result.getText());
}
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver", "chromedriver");
System.out.println("Hello");
WebScraper webSrcaper = new WebScraper();
webSrcapper.openTestSite();
webSrcapper.enter("avoir");
webSrcapper.getText();
System.out.println("Hello");
}
}
发布于 2018-07-01 13:45:09
为了检查查询的相关结果,常见的策略是加载搜索结果列表:
List<WebElement> searchResults = driver.findElements(By.xpath("//div[@id='mid']/div"));
现在您可以使用stream遍历列表并提取相关文本,方法是从每个结果的子元素中获取文本:
int[] index = {0};
searchResults.stream().forEach(result -> {
System.out.println("Printing query result of index: " + index[0]);
result.findElements(By.xpath(".//*")).stream().forEach(webElement -> {
try {
System.out.println(webElement.getText());
} catch (Exception e) {
// Do nothing
}
});
index[0]++;
});
您将获得以下输出:
https://stackoverflow.com/questions/51120445
复制相似问题