Пытаюсь парсить адреса картинок с помощью кода:
public class AlbumArtGrabber {
// ключ API
public final static String API_KEY = "******";
// ID поисковой системы
public final static String SEARCH_ENGINE = "*********";
private final static String ENCODING = "UTF-8";
// полный URL для поискового запроса
private final static String GET_URL = "https://www.googleapis.com/customsearch/v1?key="
+ API_KEY + "&cx=" + SEARCH_ENGINE + "&q=";
public static List<URL> doGoogleSearch(final String query, int page) {
if (query == null || query.trim().isEmpty() || page < 1) {
throw new IllegalArgumentException(
"Ошибка: заданы некорректные аргументы.");
}
List<URL> result = new ArrayList<URL>();
// заменяем все пробелы в поисковом запросе, если есть
String searchQuery = query.replaceAll(" ", "+");
System.out.println("Поиск начался.");
try {
// номер страцы результатов поиска Google
String start = "&start=" + String.valueOf(page);
// небходимо закодировать UTF-8 строку
searchQuery = URLEncoder.encode(searchQuery, ENCODING);
URL url = new URL(GET_URL + searchQuery + start + "&alt=json&");
// выполняем GET запрос и получаем список ссылок
// из результатов поиска
result.addAll(getListOfUrlsFormGoogleResponse(url));
System.out.println("Поиск завершен");
} catch (Exception e) {
System.err.println("Во время поиска произошла ошибка: "
+ e.getMessage());
}
return result;
}
private static List<URL> getListOfUrlsFormGoogleResponse(final URL url)
throws ProtocolException, IOException {
List<URL> result = new ArrayList<URL>();
// создаем соединение
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// заголовоки GET запроса
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
System.out.println("Строка поискового запроса: " + url.toString());
System.out.println("Ответ от сервера: ");
// ответ от сервера
// в ответе содержится различная информация, однако нам необходимо
// получить
// только URL
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
final String PARAM = "\"link\": \"";
// берем из ответа только ссылку и добавляем ее в результат
if (output.contains(PARAM)) {
String link = output.substring(
output.indexOf(PARAM) + (PARAM).length(),
output.indexOf("\","));
result.add(new URL(link));
}
}
//закрываем сетевое соединение
conn.disconnect();
return result;
}}
Получаю ответ такого вида:
{
"kind": "customsearch#result",
"title": "Astronomy Picture of the Day",
"htmlTitle": "Astronomy Picture of the Day",
"link": "https://apod.nasa.gov/apod/astropix.html",
"displayLink": "apod.nasa.gov",
"snippet": "Explanation: Normally faint and elusive, the Jellyfish Nebula is caught in this \nalluring telescopic image. Centered in the scene it's anchored right and left by \ntwo bright stars, Mu and Eta Geminorum, at the foot of the celestial twin. The \nJellyfish Nebula is the brighter arcing ridge of emission with dangling tentacles. \nIn fact, the ...",
"htmlSnippet": "Explanation: Normally faint and elusive, the Jellyfish Nebula is caught in this \u003cbr\u003e\nalluring telescopic \u003cb\u003eimage\u003c/b\u003e. Centered in the scene it's anchored right and left by \u003cbr\u003e\ntwo bright stars, Mu and Eta Geminorum, at the foot of the celestial twin. The \u003cbr\u003e\nJellyfish Nebula is the brighter arcing ridge of emission with dangling tentacles. \u003cbr\u003e\nIn fact, the ...",
"cacheId": "87TgjKwQQIYJ",
"formattedUrl": "https://apod.nasa.gov/apod/astropix.html",
"htmlFormattedUrl": "https://apod.nasa.gov/apod/astropix.html",
"pagemap": {
"cse_thumbnail": [
{
"width": "276",
"height": "182",
"src": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRe-lmsRxetMUTlcce6X6Kk2pM7o20HVyLAMHK_qwyQcJCNiwcmYJQ0yZE"
}
],
"metatags": [
{
"orgcode": "661",
"rno": "phillip.a.newman",
"content-owner": "Jerry.T.Bonnell.1",
"webmaster": "Stephen.F.Fantasia.1",
"viewport": "width=device-width, initial-scale=1"
}
],
"cse_image": [
{
"src": "https://apod.nasa.gov/apod/image/1803/IC443_HaRGB1024.jpg"
}
]
}
},
И окончательный результат, я забираю из ответа только ссылки (link):
Поиск завершен
Список ссылок из результатов поиска:
https://vk.com/kartinka_da
https://translate.yandex.ru/ocr
https://www.google.com/imghp?hl=ru
http://bipbap.ru/category/krasivye-kartinki
http://tilda.education/articles-images-for-social
https://www.1zoom.ru/%D0%A0%D0%B0%D0%B7%D0%BD%D0%BE%D0%B5/%D0%9B%D1%8E%D0%B1%D0%BE%D0%B2%D1%8C/t2/1/
http://www.astronet.ru/db/apod.html
https://apod.nasa.gov/apod/astropix.html
https://www.livejournal.com/support/faq/6.html
http://chandra.harvard.edu/photo/2017/dark/
Process finished with exit code 0
Вопрос. Как забрать другое содержимое заголовков? Нужно брать не link а src из ответа. например забрать из ответа все строчки
"src": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRe-lmsRxetMUTlcce6X6Kk2pM7o20HVyLAMHK_qwyQcJCNiwcmYJQ0yZE"
Кофе для программистов: как напиток влияет на продуктивность кодеров?
Рекламные вывески: как привлечь внимание и увеличить продажи
Стратегії та тренди в SMM - Технології, що формують майбутнє сьогодні
Выделенный сервер, что это, для чего нужен и какие характеристики важны?
Современные решения для бизнеса: как облачные и виртуальные технологии меняют рынок
Здравствуйте, можете подсказать что происходит со ссылками и объектами в этой программе(задача из Head First Java)?
Помогите, не могу разобратьсяЯ начал изучать Spring (IoC Concept), разобрал как можно конфигурировать бины через xml и отдельно через аннотации, но не пойму...
Можно ли запустить код, который написан на Java, из программы, которая написана на Python? Как, например, asm в c++А точнее, как из плагина на Питоне...
То есть пользователь видит Изменить имя: АлексейИ он может редактировать слово Алексей