dimaxus писал(а): ↑Чт мар 11, 2021 6:37 pm
Добрый вечер всем. Уважаемый Михря вчера перестал работать ваш парсер , хотя последние 3 месяца прекрасно работал. Может что в Яндексе изменили, как проверить, подправить? Или проблема только у меня?
Тоже попробовал тем парсером содрать погоду - не получилось, походу яндекс стал бороться с роботами и по тому адресу стало невозможно спарсить данные, по крайней мере у меня не получилось )
В меру своих возможностей, а они у меня весьма скудные, сделал свой парсер, если оптимизируете код и наведете в нем красоту буду благодарен, я пользуюсь как есть )
Вот код, который надо положить в скрипты и запускать по таймеру раз в час например:
Код: Выделить всё
$city = 41; // поменять на свой
$url= 'https://yandex.ru/pogoda/' . $city;
$str = file_get_contents($url);
$dom = phpQuery::newDocument($str);
// считываем данные на несколько дней вперед
foreach($dom->find(".forecast-briefly__day-link") as $key => $value){
// Преобразуем dom объект в объект phpQuery.
//Делаем сие действие с помощью метода pq(); который является аналогом ($) в jQuery.
$pq = pq($value);
// Находим в этом элементе элементы
$day[$key]["day"] = $pq->find(".forecast-briefly__name")->text();
$day[$key]["time"] = $pq->find(".forecast-briefly__date")->text();
$day[$key]["icon"] = $pq->find(".forecast-briefly__icon")->attr('src');
$day[$key]["temp_day"] = $pq->find(".forecast-briefly__temp_day .temp__value")->text();
$day[$key]["temp_night"] = $pq->find(".forecast-briefly__temp_night .temp__value")->text();
$day[$key]["condition"] = $pq->find(".forecast-briefly__condition")->text();
}
// заменить 10 на количество дней, за которые хотите иметь погоду
for ($i = 1; $i <= 10; $i++) {
// все глобальные свойства ниже создадутся автоматически, необходимо создать только weather
sg("weather.day".$i,$day[$i]["day"] );
sg("weather.time".$i,$day[$i]["time"] );
$day[$i]["icon"] = str_replace("//yastatic.net/weather/i/icons/funky/dark/", '/cms/scenes/new/icons/', $day[$i]["icon"]);
$day[$i]["icon"] = str_replace("png", "svg", $day[$i]["icon"]);
sg("weather.icon".$i,$day[$i]["icon"] );
sg("weather.temp_day".$i,$day[$i]["temp_day"] );
sg("weather.temp_night".$i,$day[$i]["temp_night"] );
sg("weather.condition".$i,$day[$i]["condition"] );
}
//считываем данные за текущий день
$pq=pq($dom->find(".fact") );
$fact["temp"] = $pq->find(".fact__temp-wrap .link .fact__temp .temp__value")->text();
$fact["icon"] = $pq->find(".fact__temp-wrap .link .icon")->attr('src');
$fact["feel"] = $pq->find(".fact__temp-wrap .link .link__feelings .term .term__value")->text();
$fact["wind"] = $pq->find(".fact__props .fact__wind-speed .term__value .wind-speed")->text();
$fact["wind_word"] = $pq->find(".fact__props .fact__wind-speed .term__value")->attr('aria-label');
$fact["wind_dir"] = $pq->find(".fact__props .fact__wind-speed .term__value .fact__unit .icon-abbr")->text();
$fact["hum"] = $pq->find(".fact__props .fact__humidity .term__value ")->text();
$fact["hum_word"] = $pq->find(".fact__props .fact__humidity .term__value ")->attr('aria-label');
$fact["press"] = $pq->find(".fact__props .fact__pressure .term__value")->text();
$fact["press_word"] = $pq->find(".fact__props .fact__pressure .term__value")->attr('aria-label');
$fact["icon"] = str_replace("//yastatic.net/weather/i/icons/funky/light/", '/cms/scenes/new/icons/', $fact["icon"]);
$fact["icon"] = str_replace("png", "svg", $fact["icon"]);
//соберем погоду по часам
$i=0; //счетчик
foreach($dom->find(".fact__hour") as $key => $value){
$pq = pq($value);
if (substr($pq->find(".fact__hour-elem .fact__hour-label")->text(),-3)==":00" ) { //если время заканчивается на целый час
// то сохраним в массив, иначе это было время восхода/заката и это включать в массив не будем
$hours[$i]["time"] = $pq->find(".fact__hour-elem .fact__hour-label")->text();
$hours[$i]["icon"]= $pq->find(".fact__hour-elem .icon")->attr('src');
$hours[$i]["temp"]= $pq->find(".fact__hour-elem .fact__hour-temp")->text();
$i=$i+1;//увеличим счетчик
}
}
$j=0;//счетчик
for ($i = 0; $i <= count($hours); $i+=6) { //выведем только кажый 6-ой час
$hours[$i]["icon"]= str_replace("//yastatic.net/weather/i/icons/funky/flat/", '/cms/scenes/new/icons/', $hours[$i]["icon"]);
$hours[$i]["icon"] = str_replace("png", "svg", $hours[$i]["icon"]);
sg("weather.hour_time".$j,$hours[$i]["time"] );
sg("weather.hour_icon".$j,$hours[$i]["icon"] );
sg("weather.hour_temp".$j,$hours[$i]["temp"] );
$j+=1;
}
sg("weather.fact_temp",$fact["temp"] );
sg("weather.fact_icon",$fact["icon"] );
sg("weather.fact_feel",$fact["feel"] );
sg("weather.fact_wind",$fact["wind"] );
sg("weather.fact_wind_word",$fact["wind_word"] );
sg("weather.fact_wind_dir",$fact["wind_dir"] );
sg("weather.fact_hum",$fact["hum"] );
sg("weather.fact_hum_word",$fact["hum_word"] );
sg("weather.fact_press",$fact["press"] );
sg("weather.fact_press_word",$fact["press_word"] );
// заменить 10 на количество необходимых прогнозируемых дней
for ($i = 1; $i <= 10; $i++) {
// все глобальные свойства ниже создадутся автоматически, необходимо создать только weather
sg("weather.day".$i,$day[$i]["day"] );
sg("weather.time".$i,$day[$i]["time"] );
$day[$i]["icon"] = str_replace("//yastatic.net/weather/i/icons/funky/dark/", '/cms/scenes/new/icons/', $day[$i]["icon"]);
$day[$i]["icon"] = str_replace("png", "svg", $day[$i]["icon"]);
sg("weather.icon".$i,$day[$i]["icon"] );
sg("weather.temp_day".$i,$day[$i]["temp_day"] );
sg("weather.temp_night".$i,$day[$i]["temp_night"] );
sg("weather.condition".$i,$day[$i]["condition"] );
}
//восход, закат
$sunrise=pq($dom->find(".sun-card__sunrise-sunset-info_value_rise-time") );
$sunrise=substr($sunrise->text() , -5); //нужны только последние 5 символов
$sunset =pq($dom->find(".sun-card__sunrise-sunset-info_value_set-time") );
$sunset=substr($sunset->text(), -5); //нужны только последние 5 символов
sg("weather.sunrise",$sunrise);
sg("weather.sunset",$sunset);
sg("weather.updated", date('l jS \of F Y h:i:s A'));