繁体   English   中英

如何使用Java(Android)从网站抓取数据?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM