【问题标题】:How to get a value from a webpage using java如何使用java从网页中获取值
【发布时间】:2016-03-16 14:57:15
【问题描述】:

在以下 URL http://www.manta.com/c/mx4s4sw/bowflex-academy 中,我想获取 SIC 代码。这是我的代码和错误:

public static void main(String[] args) {
    try {
        Document doc = Jsoup.connect("http://www.manta.com/c/mx4s4sw/bowflex-academy").ignoreHttpErrors(true).get();
        String textContents = doc.select("itemprop").first().text();
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
}

Exception in thread "main" java.lang.NullPointerException at com.inndata.connection.GoogleScraperDemo.main(GoogleScraperDemo.java:22)

【问题讨论】:

  • 访问网站被阻止?
  • 我可以从我的浏览器访问该 URL。
  • 为什么你认为doc.select("itemprop") 会返回任何东西?
  • 我想要来自 标签的 SIC 代码,我正在尝试获取值: SIC代码 7991,健身设施

标签: java html css


【解决方案1】:

选择器"itemprop" 不正确。

文档中的 SIC 代码位于 HTML 块中,如下所示:

  <tr>
      <th class="text-left" style="width:30%;">SIC Code</th>
      <td rel="sicDetails"><span itemprop="isicV4">7991</span>, Physical Fitness Facilities</td>
  </tr>

选择器应该类似于

"span[itemprop='isicV4']"

我没有测试过这个。此外,只要网站所有者更改该行的布局或 itemprop 值,这就会中断。您可能会更喜欢查找字符串 SIC Code,然后在下方搜索,但任何此类抓取都可能会因网站更改而变得脆弱,除了事后做出反应外,您无能为力。

【讨论】:

  • 我试过这样,试试 { Document doc = Jsoup.connect("manta.com/c/mx4s4sw/…; Elements spans = doc.select("span[itemprop='isicV4']"); System.out. println(spans.isEmpty()); } catch (IOException e) { e.printStackTrace(); } } 当我打印值时得到 true
【解决方案2】:

您尝试抓取的网站不允许抓取。如果您使用 Jsoup、HtmlUnit 等第三方工具,则会将其检测为 bot。

所以尝试使用java的内置库“java.net”来获取网页,你很好。

以下是一些关键步骤 -

  1. 从 url 字符串创建 URL 对象 -

    URL url = new URL(targetPageURLString);

  2. 通过 URL 打开 http 连接 -

    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

  3. 从输入流中读取网络响应 -

    InputStream urlStream = urlConnection.getInputStream();

  4. 从流中逐字节读取响应后,将此字节数组转换为字符串。

  5. 使用正则表达式,您可以获得所需的信息/内容

【讨论】:

    猜你喜欢
    • 2020-10-13
    • 2021-04-18
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 2015-08-27
    • 2020-08-02
    • 1970-01-01
    • 2021-06-22
    相关资源
    最近更新 更多