【发布时间】:2014-03-13 22:29:53
【问题描述】:
我有以下问题。 我正在使用 jSoup 从页面中提取图像(我正在尝试下载漫画),然后转到下一页,下载下一个图像等等...... 通常,我从按钮中提取 URL 到下一页:
<a href="2.html" class="btn next_page"><span></span>next page</a>
但是当漫画的一章结束时,当我点击页面上的按钮时,它会通过 JavaScript 将我重定向到下一章:
<a href="javascript:void(0);" onclick="next_chapter()" class="btn next_page"><span></span>next page</a>
有没有办法提取到下一页的链接?之前有人建议我使用 Selenium,我尝试了几次都失败了。也许有人有什么建议?
好的,这是我的代码 sn-p:
while (endManga) {
Document doc = Jsoup.connect(link).get();
String title = doc.title();
System.out.println(title);
Element nextButtonDiv = doc.getElementById("top_center_bar");
Elements nextButton = nextButtonDiv.select("a[href]");
if (nextButton.isEmpty())
endManga = true;
else {
Element nextLinkElement = nextButton
.get(nextButton.size() - 1);
String nextLink;
//here is the problem - at some point, when one chapter ends,
//there isn't link to the next one, only "onclick="next_chapter()"" javascript function
if (nextLinkElement.attr("href").length() < 10)
nextLink = nextLinkElement.attr("abs:href");
else
nextLink = nextLinkElement.attr("href");
link = nextLink;
}
Element content = doc.getElementById("viewer");
Elements jpgs = content.select("img[src$=.jpg]");
BufferedImage image = null;
if (jpgs.isEmpty()) {
System.out.println("empty!!");
counterVolume++;
} else {
for (Element imageURL : jpgs) {
image = ImageIO.read(new URL(imageURL.attr("src")));
ImageIO.write(image, "jpg", new File("manga/"
+ counterVolume + "_" + counterPage++ + ".jpg"));
System.out.println("zgrane - volume: " + counterVolume
+ " , page: " + counterPage);
}
}
}
这是我使用硒的代码:
WebDriver driver = new HtmlUnitDriver();
driver.get("link_to_page_with_javascript_function");
WebElement element = driver.findElement(By.id("top_center_bar"));
List<WebElement> el = element.findElements(By.tagName("a"));
System.out.println(element.getTagName());
for(WebElement e : el){
if(e.getText().equals("next page")){
//here I have the button, which clicked redirects me to next chapter
//how can I extract the link from this function??
e.click();
}
}
【问题讨论】:
-
您想在点击元素之前找出下一页的URL吗?
-
@Louis 我的印象是这个问题是特定于 Javascript 的。抱歉,如果有错误,如果您认为合适,请随时回复。
-
我根本不想点击它。我想在不打开浏览器的情况下获取 URL。我想从下一页获取使用 jSoup 提取下一个图像的链接。我不知道你是否得到它;p 如果没有,我会将代码 sn-p 包含到我的应用程序中。
标签: java javascript selenium jsoup