[英]How to extract text from specific rows in nested tables with Jsoup
我正在使用Jsoup從網站提取文本,但是我不知道如何正確地獲取嵌套表中的特定數據行。 我需要在表示“ 屬性地址:”和“ 郵寄地址:”的部分之后獲取純文本,以便我可以存儲數據。
這是我正在解析的HTML源代碼:
<table width="730" border="0" cellspacing="0" cellpadding="2">
<tr>
<td><table width="730" border="0" cellspacing="0" cellpadding="2">
<tr>
<td><h1>Property Information</h1>
<table width="758">
<tr>[IRRELEVANT]</tr>
<tr>[IRRELEVANT]</tr>
<tr>
<td colspan="3"><strong>Property Address:</strong> !!THIS PLAIN TEXT HERE IS WHAT I NEED!! DATA1</td>
<td> </td>
</tr>
<tr>
<td colspan="3"><strong>Mailing Address:</strong>!!NEED THIS TOO!! DATA2</td>
<td> </td>
</tr>
<tr>[IRRELEVANT]</tr>...................
我當時使用它作為模板,但是它不起作用,我也不知道如何使它起作用。
Document documentSerialNumberPageData = Jsoup.connect(stringURLOfSerialNumberPage).get(); //connect to serial number page
Elements elementsSerialNumberPageData = documentSerialNumberPageData.select("#tabletext tbody > tr > td > tbody > tr > td > tbody > tr > td"); //this is not even remotely correct... :(
Element elementAddress = elementsSerialNumberPageData.get(0);
System.out.println(elementAddress.text());
我對HTML / CSS的了解非常有限,但是我精通Java。 有什么建議么? 謝謝! 全文在這里: https : //github.com/PhotonPhighter/NODScraper/blob/master/src/nodscraper/Main.java
您可以嘗試以下方法:
Elements innerTable = documentSerialNumberPageData.select("body > table:nth-child(2) > tbody > tr > td > table > tbody > tr > td > table:nth-child(2)");
String propertyAddress = ((org.jsoup.nodes.TextNode)innerTable.select("tr:nth-child(3) > td > strong").first().nextSibling()).text();
String mailingAddress = ((org.jsoup.nodes.TextNode)innerTable.select("tr:nth-child(4) > td > strong").first().nextSibling()).text();
首先,選擇table
,然后在第三個tr
的第一個td
中選擇strong
標簽,然后選擇該標簽的下一個同級,然后將text()
放入其中。 我們對第四tr
做同樣的事情。
JSoup將使用text()
轉換
放入空格,如果您不願意,也可以調用toString()
。
希望對您有所幫助。
PS:我可以建議一個把戲嗎? 您可以使用Chrome或Firefox的開發人員工具在html頁面中找到標簽,然后右鍵單擊並Copy CSS Path
。 這將為您提供可在JSoup中使用的選擇器!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.