+-

我想从这个动态网站上使用Selenium和jsoup提取一些信息.要获取我要提取的信息,我必须单击“ Detailsöffnen”按钮.第一张图片显示了在单击按钮之前的网站,第二张图片显示了在单击按钮之后的网站.红色标记的信息是我要提取的信息.
我首先尝试仅使用Jsoup提取信息,但是由于有人告诉我Jsoup无法处理动态内容,所以现在我尝试像在源代码中看到的那样使用硒和Jsoup提取信息.但是,我不确定硒是否是正确的选择,因此也许还有其他方法可以更简单地提取我需要的信息,但是使用Java来完成这一点很重要.
接下来的两张图片显示了单击按钮之前和单击按钮之后的html代码.
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver(createFirefoxProfile());
driver.get("http://www.seminarbewertung.de/seminar-bewertungen?id=3448");
//driver.findElement(By.cssSelector("input[type='button'][value='Details öffnen']")).click();
WebElement webElement = driver.findElement(By.cssSelector("input[type='submit'][value='Details öffnen'][rating_id='2318']"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", webElement);
String html_content = driver.getPageSource();
//driver.close();
Document doc1 = Jsoup.parse(html_content);
System.out.println("Hallo");
Elements elements = doc1.getAllElements();
for (Element element : elements) {
System.out.println(element);
}
}
private static FirefoxProfile createFirefoxProfile() {
File profileDir = new File("/tmp/firefox-profile-dir");
if (profileDir.exists())
return new FirefoxProfile(profileDir);
FirefoxProfile firefoxProfile = new FirefoxProfile();
File dir = firefoxProfile.layoutOnDisk();
try {
profileDir.mkdirs();
FileUtils.copyDirectory(dir, profileDir);
} catch (IOException e) {
e.printStackTrace();
}
return firefoxProfile;
}
使用此源代码,我找不到要提取的信息的div元素.
如果有人可以帮助我,那真是太好了.
最佳答案
的确,如果Jsoup是由javascript生成的,则Jsoup无法处理动态内容,但是在您的情况下,该按钮正在发出Ajax请求,而Jsoup可以很好地做到这一点.
我建议打个电话以重新整理按钮及其ID,然后成功调用(Ajax帖子)以检索详细信息(评论或其他内容).
代码可以是:
Document document = Jsoup.connect("http://www.seminarbewertung.de/seminar-bewertungen?id=3448").get();
//we retrieve the buttons
Elements select = document.select("input.rating_expand");
//we go for the first
Element element = select.get(0);
//we pick the id
String ratingId = element.attr("rating_id");
//the Ajax call
Document document2 = Jsoup.connect("http://www.seminarbewertung.de/bewertungs-details-abfragen")
.header("Accept", "*/*")
.header("X-Requested-With", "XMLHttpRequest")
.data("rating_id", ratingId)
.post();
//we find the comment, and we are done
//note that this selector is only as a demo, feel free to adjust to your needs
Elements select2 = document2.select("div.ratingbox div.panel-body.text-center");
//We are done!
System.out.println(select2.text());
此代码将打印所需的代码:
Das Eingehen auf individuelle Bedürfnisse eines jeden einzelnen Teilnehmer scheint mir ein Markenzeichen von Fromm zu sein. Bei einem früheren Seminar habe ich dies auch schon so erlebt!
希望对您有所帮助.
祝新年快乐!
点击查看更多相关文章
转载注明原文:Java-使用Jsoup和Selenium进行Web抓取 - 乐贴网