关于java:使用jsoup从html中获取url | 珊瑚贝

Fetch urls from html with jsoup


我正在尝试使用 jsoup 获取一个 url,以便从该 url 下载一个图像,但由于某种原因它不起作用。

我首先尝试找到”div class=”rg_di””第一次出现在 html 文件中的位置,
而不是获取紧随其后的网址:

1
a href=“http://www.google.co.il/imgres?imgurl=http://michellepicker.files.wordpress.com/2011/03/grilled-chicken-mexican-style.jpg&imgrefurl=http://michellepicker.wordpress.com/2011/04/25/grilled-chicken-mexican-style-black-beans-guacamole/&h=522&w=700&tbnid=4hXCtCfljxmJXM:&zoom=1&docid=ajIrwZMUrP5_GM&ei=iVOqVPmDDYrnaJzYgIAM&tbm=isch”

这是 html 的 url:

查看来源:https://www.google.co.il/search?q=烤墨西哥鸡

  • 您收到错误 403 吗?
  • 你解决问题了吗?


我编辑了您的代码以消除错误 403

而不是这个:

1
doc = Jsoup.connect(url).get();

写这个:

1
doc = Jsoup.connect(url).userAgent(“Mozilla”).get();

似乎链接是动态生成的。 Jsoup 获取不包含 .rg_di 类的 html,因此

1
doc.select(“div.rg_di”).first();

返回null,我们得到nullpointerexception。

jsoup下载的html片段

1
<img height=“104” src=“https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcT-pctOxpuUcdq118aFU3s2miRfUa6Ev8eF-UsxARHV-vbcOUV8byEtt2YT” width=“140”>

我们能做的最好的就是获取每个 img 标签并遍历它们,我们得到图标链接列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Document doc = Jsoup.connect(url).userAgent(“Mozilla”).get();
Elements imgs = doc.select(“img”);
for(Element img : imgs){
    String link  = img.attr(“src”);
    System.out.println(link);
}

/textinputassistant/tia.png
https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcT-pctOxpuUcdq118aFU3s2miRfUa6Ev8eF-UsxARHV-vbcOUV8byEtt2YT
https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQMq354p43ddqPcpV9-q_05YkmY7XUPgv6Sl2oQLqFxQ5-IkpGAAuFTLMM
https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTW-RinkkW_fBdlHzTJn6vNmR85TR58geQgfjQnEJmOqzjq0Oi-z-8zXjg
https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRUXLzKi3UyQ6mF9JD20Z1jYNhVxQz7tkhJIEGOL3kua8ptoQrvo8-Nco_X
https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTverQlzF_hauCabscWF4wHLb_q7g9M_UDKO6LaldSRHhsTj7CxtVF2yvc

解析动态内容有很多解决方案。链接

编辑 1

我实现了 htmlunit 来渲染一个页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.io.IOException;
import java.net.MalformedURLException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class Main {
    public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
        String url =“https://www.google.co.il/search?q=grilled+mexican+chicken&es_sm=93&source=lnms&tbm=isch&sa=X&ei=h1OqVOH6B5bjaqGogvAP&ved=0CAgQ_AUoAQ&biw=1920&bih=955”;
        WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24); // Chrome not working
        HtmlPage page = webClient.getPage(url);
        try {
            Document doc = Jsoup.parse(page.asXml());
            Elements divs = doc.select(“.rg_di”);
            for(Element div : divs){
                Element img = div.select(“a”).get(0);
                String link  = img.attr(“href”);
                System.out.println(link);
            }
        } catch (Exception e) {
             e.printStackTrace();
        }
    }
}

htmlunit 有自己的 html 解析 api,但我会坚持使用更直观的 jsoup

编辑 2

只要你的目标是在 Android 设备上渲染和解析 HTML 页面,HTMLUnit 就不是一个好的选择 source


HtmlUnit uses Java classes that are not available on Android.
On top of that, HtmlUnit uses a bunch of other libraries, some of which may have their own dependencies on these libraries. So, as awesome as HmlUnit is, I think getting it to run on Android may not be an easy task.

  • 您可以尝试这种解决方案。或者
  • 您可以折磨自己并尝试此解决方案(最好不要)。或者
  • 如果考虑到这个人的经验,重新设计你的软件架构会更好:

  • 创建呈现网页并解析它的java服务器。 HTMLUnit Jsoup
  • 将解析后的数据以 JSON 格式保存在服务器的文件系统中。格森
  • 创建 servlet,当 android 应用程序请求它时发送 JSON 文件。
  • 非常感谢您的回答!我尝试查看链接中的所有答案。这一切都非常复杂,即使”httmlunit”也不容易理解如何实现,您是否有机会使用 httmlunit 发布工作示例?
  • @maor 我一有空就会弄清楚如何使用 htmlunit
  • 首先非常感谢! -第二,我试过了,它崩溃了.. ” ” Exception Ljava/lang/NoClassDefFoundError;在初始化 Lcom/gargoylesoftware/htmlunit/WebClient” 时抛出 – 知道为什么吗?
  • 您是否已将 htmlunit jar 包含到您的类路径中?下载
  • 你的意思是我把它添加到我项目的 libs 文件夹中了吗? – 如果你是这个意思,那么是的,我添加了 htmlunit-2.15、htmlunit-core-js-2.15、httpclient-4.3.3、httpcore-4.3.2 和 httpmime-4.3.3。


来源:https://www.codenong.com/27794661/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9322.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?