我在试着把这段文字
使用下面的代码。但是,输出表现得好像嵌套的跨度不存在一样。
Elements tags = document.select("div[id=tags]");
for (Element tag:tags){
Elements child_tags = tag.getElementsByTag("class");
String key = tag.html();
System.out.println(key); //only as a test
for (Element child_tag:child_tags){
System.out.println("\t" + child_tag.text());
}
我的输出是
<hr />Tags:
<span id="category"></span>
<span id="voteSelector" class="initially_hidden"> <br /> </span>
发布于 2017-11-25 11:22:02
假设您正在https://chesstempo.com/chess-problems/15上尝试代码,您想要的数据如下图所示
现在,无论作为浏览器中作为源代码呈现的数据是什么,您都可以在浏览器中按CTRL+U
键来获取数据,这将打开一个新的窗口,在该窗口中将显示Jsoup将获得的实际内容。现在来问您的问题,您试图检索的部分在浏览器源代码中不存在,请按CTRL+U
检查。
如果内容是使用JAVASCRIPT呈现的,这些内容对JSOUP是不可见的,因此您必须使用其他东西来运行javascript并向您提供详细信息。
JSoup不运行Javascript,也不是浏览器。
编辑
使用SELENIUM实现了转机。下面是获取url的确切源代码的工作代码和您正在寻找的所需数据:
import java.io.IOException;
import java.io.PrintWriter;
import org.json.simple.parser.ParseException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class JsoupDummy {
public static void main(String[] args) throws IOException, ParseException {
System.setProperty("webdriver.gecko.driver", "D:\\thirdPartyApis\\geckodriver-v0.19.1-win32\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
try {
driver.get("https://chesstempo.com/chess-problems/15");
Document doc = Jsoup.parse(driver.getPageSource());
Elements elements = doc.select("span.ct-active-tag");
for (Element element:elements){
System.out.println(element.html());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
/*write.flush();
write.close();*/
driver.quit();
}
}
}
您需要selenium web驱动程序硒Web驱动程序,它模拟浏览器行为,并允许您呈现脚本编写的html内容。
发布于 2017-11-22 13:34:35
Elements child_tags = tag.getElementsByTag("class");
使用这一行,您将尝试获得一个标记类(即<class>...</class>
)的元素,该元素并不存在。将这一行改为:
Elements child_tags = tag.getElementsByClass("tag");
若要按属性值class = tag获取元素,请执行以下操作:
Elements child_tags = tag.getElementsByTag("span");
通过标记名称= span获取元素。
https://stackoverflow.com/questions/47435187
复制相似问题