[英]How to get text from nested span using Jsoup?
我正在嘗試獲取范圍內的文本
在下面使用此代碼。 但是輸出的行為似乎不存在嵌套的跨度
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>
Elements child_tags = tag.getElementsByTag("class");
在這行代碼中,您嘗試獲取一個標記類為<class>...</class>
的元素,該元素不存在。 將該行更改為:
Elements child_tags = tag.getElementsByClass("tag");
通過class = tag的屬性值獲取元素或:
Elements child_tags = tag.getElementsByTag("span");
通過標簽名稱= span獲取元素。
假設您正在嘗試https://chesstempo.com/chess-problems/15上的代碼,並且所需的數據如下圖所示
現在,使用Jsoup,您將獲得在瀏覽器中呈現為源代碼的任何數據,為進行確認,您可以在瀏覽器中按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驅動程序Selenium Web Driver ,它可以模擬瀏覽器的行為,並允許您呈現腳本編寫的html內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.