Java JSoup错误提取URL

时间:2016-04-21 20:41:36

标签: java jsoup

我正在创建一个应用程序,它可以让我从特定网站获取值到控制台。该值来自<span>元素,我使用 JSoup

我的挑战与此错误有关:

  

获取网址时出错

这是我的Java代码:

public class TestSl {
    public static void main(String[] args) throws IOException {
        Document doc = Jsoup.connect("https://stackoverflow.com/questions/11970938/java-html-parser-to-extract-specific-data").get();
        Elements spans = doc.select("span[class=hidden-text]");
        for (Element span: spans) {
            System.out.println(span.text());
        }
    }
}

这是控制台上的错误:

  

线程中的异常&#34; main&#34; org.jsoup.HttpStatusException:HTTP错误提取URL。状态= 403,网址= Java Html parser to extract specific data?       at org.jsoup.helper.HttpConnection $ Response.execute(HttpConnection.java:590)       at org.jsoup.helper.HttpConnection $ Response.execute(HttpConnection.java:540)       在org.jsoup.helper.HttpConnection.execute(HttpConnection.java:227)       在org.jsoup.helper.HttpConnection.get(HttpConnection.java:216)       在TestSl.main(TestSl.java:19)

我做错了什么,如何解决?

1 个答案:

答案 0 :(得分:8)

设置用户代理标头:

.userAgent("Mozilla")

示例:

Document document = Jsoup.connect("https://stackoverflow.com/questions/11970938/java-html-parser-to-extract-specific-data").userAgent("Mozilla").get();
Elements elements = document.select("span.hidden-text");
for (Element element : elements) {
  System.out.println(element.text());
}
  

Stack Exchange

     

收件箱

     

声誉和徽章

来源:https://stackoverflow.com/a/7523425/1048340

也许这是相关的:https://meta.stackexchange.com/questions/277369/a-terms-of-service-update-restricting-companies-that-scrape-your-profile-informa