[英]How do I scrape data from a website using Java (Android)?
我的Android應用將從電話號碼獲取運營商信息。 我打算使用Jsoup(或另一個Java HTML解析器)來刮擦表中顯示的運營商信息。
我正在嘗試從fonefinder.net抓取
查詢URL格式為:
http://www.fonefinder.net/findome.php?npa=**first 3 digits**&nxx=**next 3 digits**&thoublock=**final 4 digits**
頁面的HTML是一個簡單的表格(請參見下文)。 我正在嘗試從第二行第五列提取數據,其中鏈接以以下格式出現
http://fonefinder.net/(CARRIER_NAME).php
其中CARRIER_NAME是“ verizon”之類的值。 我需要幫助弄清楚如何提取此數據。
<table border="3" cellspacing="2" cellpadding="2" bgcolor="#FFFFCC">
<tbody>
<tr bgcolor="#7093DB" align="CENTER">
<th>
Area Code
</th>
<th>Prefix</th>
<th>
City/Switch Name
<br>
(Click for city search)
</th>
<th>
State/Prov.
<br>
Area Map
</th>
<th>
Telephone Company
<br/>
Web link
</th>
<th>
Telco
<br/>
Type
</th>
<th>
Map/Zip
<br/>
Detail
</th>
</tr>
<tr>
<td>
**first 3 digits**
</td>
<td>
**next 3 digits**
</td>
<td>
City Name
</td>
<td>
State Name
</td>
<td>
<a href="http://fonefinder.net/CARRIER_NAME.PHP">carrier name</a>
</td>
<td>WIRELESS PROV</td>
<td>
map
</td>
</tr>
</tbody>
</table>
我編寫的代碼大量使用了Jsoup的選擇器語法來按名稱解析標簽,但是您也可以按CSS類,id,屬性等進行解析。 Jsoup選擇器語法文檔包含您可以使用的選擇器的完整列表。
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class StackOverflowQuestion {
public static void main(String[] args) {
try {
// get the tables on this page, note I masked the phone number
Document doc = Jsoup.connect("http://www.fonefinder.net/findome.php?npa=###&nxx=###&thoublock=####").get();
Elements tables = doc.select("table");
// get the second table, 0 indexed
Element secondTable = tables.get(1);
// get the columns
Elements tds = secondTable.select("td");
//get the 5th column, 0 indexed
Element fifthTd = tds.get(4);
//get the link in this column
Element link = fifthTd.select("a").first();
//print out the URL
System.out.println(link.attr("href"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.