使用无头浏览器进行 Android 网页抓取 [英] Android Web Scraping with a Headless Browser

查看:69
本文介绍了使用无头浏览器进行 Android 网页抓取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了一天时间研究一个可以用来完成以下任务的库:

I have spent a day on researching a library that can be used to accomplish the following:

  • 像在后台一样检索网页的完整内容,而无需将结果呈现到视图中.
  • 例如,该库应该支持在初始 HTML 加载后触发 ajax 请求以加载一些额外结果数据的页面.
  • 我需要从生成的 html 中获取 xpath 或 css 选择器形式的元素.
  • 将来我可能还需要导航到下一页(触发事件、提交按钮/链接等)

这是我尝试过但没有成功的方法:

Here is what I have tried without success:

  • Jsoup:效果很好,但不支持 javascript/ajax(所以它不会加载整页)
  • Android 内置 HttpEntity:javascript/ajax 与 jsoup 存在同样的问题
  • HtmlUnit:看起来正是我需要的,但在几个小时后无法让它在 Android 上运行(其他用户尝试加载 12MB+ 的 jar 文件失败.我自己加载了完整的源代码并仅将其作为项目库引用发现Android中不存在Applets和java.awt(由HtmlUnit使用)之类的东西.
  • Rhino - 我觉得这很令人困惑,不知道如何让它在 Android 中工作,即使它是我正在寻找的东西.
  • Selenium 驱动程序:看起来它可以工作,但您没有直接的方法以无头方式实现它,因此您没有将实际的 html 显示到视图中.

我真的希望 HtmlUnit 能够工作,因为它似乎最适合我的解决方案.有没有什么方法或至少我错过了另一个适合我需要的图书馆?

I really want HtmlUnit to work as it seems the best suited for my solution. Is there any way or at least another library I have missed that is suitable for my needs?

我目前使用的是 Android Studio 0.1.7,如果需要,可以转移到 Ellipse.

I am currently using Android Studio 0.1.7 and can move to Ellipse if needed.

提前致谢!

推荐答案

好吧,2 周后我承认失败,并且正在使用目前对我很有效的解决方法.

Ok after 2 weeks I admit defeat and are using a workaround which works great for me at the moment.

问题:
将 HTMLUnit 移植到 Android 太困难了(或者至少以我的专业水平).我确信它是一个值得的项目(对于有经验的 Java 程序员来说并不费时).我给 HTMLUnit 的人发了电子邮件,他们评论说他们没有研究移植或将涉及哪些工作,但建议任何想要开始这样一个项目的人都应该向他们的邮件列表发送一条消息,让更多的开发人员参与其中(http://htmlunit.sourceforge.net/mail-lists.html).

解决方法:
我使用android内置的WebView并覆盖Webview类的onPageFinished方法来注入Javascript,在页面完全加载后抓取所有的html.Webview 还可以用于调用其他 javascript 操作、单击按钮、填写表单等.

The workaround:
I used android's built in WebView and overrided the onPageFinished method of Webview class to inject Javascript that grabs all the html after the page has fully loaded. Webview can also be used to called futher javascript actions, clicking buttons, filling in forms etc.

代码:

webView.getSettings().setJavaScriptEnabled(true);
MyJavaScriptInterface jInterface = new MyJavaScriptInterface(context);
webView.addJavascriptInterface(jInterface, "HtmlViewer");

webView.setWebViewClient(new WebViewClient() {

@Override
public void onPageFinished(WebView view, String url) {

   //Load HTML
   webView.loadUrl("javascript:window.HtmlViewer.showHTML
       ('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}

webView.loadUrl(StartURL);
ParseHtml(jInterface.html);   

public class MyJavaScriptInterface {

    private Context ctx;
    public String html;

    MyJavaScriptInterface(Context ctx) {
        this.ctx = ctx;
    }

    @JavascriptInterface
    public void showHTML(String _html) {
        html = _html;
    }
}

这篇关于使用无头浏览器进行 Android 网页抓取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆