如何以编程方式在 Android 中搜索图像?

How to search for images in Android Programmatically?

我的 Activity 中有一些 EditTexts。第一个文本用于 title,第二个文本用于 author。现在用户从第二个编辑文本中失去焦点ie author。我想获取与该内容(标题和作者)相关的图像。所以我做了什么,我连接了 title and author name 并制作了 HTTP request using Volley。然后我打印了 response.But 响应是如此不可预测,以至于我无法从中获取图像。

try {
        String googleImageUrl = "http://images.google.com/images?q=";
        String query = URLEncoder.encode(title + " " + author, "utf-8");
        String url = googleImageUrl + query;
        Toast.makeText(context, url, Toast.LENGTH_SHORT).show();
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);

  // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        post_des.setText("Response is: " + response);
                        Log.i("Show me something awesome dude", response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                post_des.setText("That didn't work!");
            }
        });
 // Add the request to the RequestQueue.
        queue.add(stringRequest);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

响应是这样的:

Response is: <!doctype html><html itemscope="" itemtype="http://schema.org/SearchResultsPage" lang="en-IN"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><link href="/images/branding/product/ico/googleg_lodp.ico" rel="shortcut icon"><title>something something - Google Search</title><style>#gb{font:13px/27px Arial,sans-serif;height:30px}#gbz,#gbg{position:absolute;white-space:nowrap;top:0;height:30px;z-index:1000}#gbz{left:0;padding-left:4px}#gbg{right:0;padding-right:5px}#gbs{background:transparent;position:absolute;top:-999px;visibility:hidden;z-index:998;right:0}.gbto #gbs{background:#fff}#gbx3,#gbx4{background-color:#2d2d2d;background-image:none;_background-image:none;background-position:0 -138px;background-repeat:repeat-x;border-bottom:1px solid #000;font-size:24px;height:29px;_height:30px;opacity:1;filter:alpha(opacity=100);position:absolute;top:0;width:100%;z-index:990}#gbx3{left:0}#gbx4{right:0}#gbb{position:relative}#gbbw{left:0;position:absolute;top:30px;width:100%}.gbtcb{position:absolute;visibility:hidden}#gbz .gbtcb{right:0}#gbg .gbtcb{left:0}.gbxx{display:none........like wise

我期待得到一份 Html 文档。 那么如何对带有内容(标题和作者)的图像进行 HTTP 请求。

编辑 通俗易懂,

假设我在 images.google.com,我在搜索栏中输入了一些内容,然后进行搜索,现在我想要 Google return 的数据作为 Url of the images on that webpage(我在后端做所有这些,没有向用户显示。) 我认为现在可以理解了:)

您得到了 html 但整个搜索页面。您可以使用 css selectors 和 [JSOUP 库][2](易于使用)检索图片的 url。只需转到 Chrome 浏览器,然后选择设置 - 更多工具 - 开发人员工具。然后在一张图片上点击鼠标右键,选择inspect然后你会看到哪个容器是图片,什么div包含图片的srcurl然后你右击这个div 并选择 copy css selector。然后与图书馆合作。

但请注意,如果他们更改页面 html,这不切实际,因为您的代码会出错。为此,您最好使用特定的 api,例如上面评论中建议的 Google 自定义搜索 API。

要将图像放入 UI,您需要获取其 url 地址,然后您可以使用 GlidePicasso 甚至 Volley

// Retrieves an image with Volley specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
    new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap bitmap) {
            mImageView.setImageBitmap(bitmap);
        }
    }, 0, 0, null,
    new Response.ErrorListener() {
        public void onErrorResponse(VolleyError error) {
            mImageView.setImageResource(R.drawable.image_load_error);
        }
    });

编辑:

这是 CSS google 搜索页面 img.rg_ic 上所有图像的选择器。使用 Jsoup 和此选择器,您将可以访问页面上的所有图像标签

Jsoup 示例:

Document doc = Jsoup.connect(your link string).get();
Elements imgs = doc.select("img");//the selector
for (Element img : imgs) {
  //add img urls to String array and then use to get imgs with them
  String s = img.attr("src");
  arr.add(s);
}

[![在此处输入图片描述][3]][3]

编辑2:

您的代码有更改:

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

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

import java.io.IOException;

public class MainActivity extends AppCompatActivity {


TextView textView;
String googleImageUrl = "https://www.google.co.in/search?biw=1366&bih=675&tbm=isch&sa=1&ei=qFSJWsuTNc-wzwKFrZHoCw&q=";
ArrayList<String> urls = new ArrayList<>();
String url;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            Log.i("someething" , "something");
            getImages("https://www.google.co.in/search?biw=1366&bih=675&tbm=isch&sa=1&ei=qFSJWsuTNc-wzwKFrZHoCw&q=somethingsomething");
        }
    });
}

private void getImages(String url) {
    Document doc = null;
    try{
        doc = Jsoup.connect(url).get();
    }catch (IOException e){
        e.printStackTrace();
    }
    Elements imgs = doc.select("img");
    System.out.println("Damn images"+imgs);
    for (Element img : imgs){
        Log.d("image-src", img.attr("data-src"));//changed `src` to `data-src`
    }

}

}

您可以使用 Jsoup 获得 google 搜索图像的列表。Ì。在此处查看官方网站 https://jsoup.org/

/**
 * Extract images from google as ArrayList.
 *
 * @param searchQuery is the string to search for
 * @return returnedURLS is the List of urls
 */
private List<String> extractImagesFromGoogle(String searchQuery) throws IOException {

    final String encodedSearchUrl = "https://www.google.com/search?q=" + URLEncoder.encode(searchQuery, "UTF-8") + "&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiUpP35yNXiAhU1BGMBHdDeBAgQ_AUIECgB";

    Document document = Jsoup.connect(encodedSearchUrl).get();
    String siteResponse = document.toString();

    List<String> returnedURLS = new ArrayList<String>();
    // parse the object and query the values (the urls) for specific keys ("ou")
    Pattern pattern = Pattern.compile("\"ou\":\"(.*?)\"");
    Matcher matcher = pattern.matcher(siteResponse);

    while (matcher.find()) {
        returnedURLS.add(matcher.group(1));
    }

    return returnedURLS;
}

    // Test it now:
    List<String> retrievedURLS = new ArrayList<String>();

    try {
        retrievedURLS = extractImagesFromGoogle("pyramids");
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(">> List Size: " + retrievedURLS.size());
    System.out.println(">> List of images urls: " + retrievedURLS);