Заметки

Да, язык указать можно используя параметр &accept-language=

Пример для получения английского результата:

https://nominatim.openstreetmap.org/search?q=56.94588160023082%2C24.110984399999996&addressdetails=1&limit=20&exclude_place_ids=183159070&format=xml&accept-language=en

Тот же результат на польском:

https://nominatim.openstreetmap.org/search?q=56.94588160023082%2C24.110984399999996&addressdetails=1&limit=20&exclude_place_ids=183159070&format=xml&accept-language=pl

По умолчанию Selenium берет тот chrome, который установлен в системе. Однако бывают случаи, когда необходимо указать другую версию браузера, к примеру портативную. 

Рассмотрим небольшой пример кода PHP, как это можно сделать: 

$chromeOptions = new ChromeOptions();
$chromeOptions->setBinary('C:\test\chrome.exe');
$chromeSettings = [];
$chromeDriver = 'C:\test\chromedriver';
$client = Client::createChromeClient($chromeDriver, $chromeSettings,
[
'capabilities' => [
ChromeOptions::CAPABILITY => $chromeOptions,
],
]);

где  'C:\test\chrome.exe' - путь до вашего исполняемого chrome.exe

$chromeDriver - путь до драйвера,  $chromeSettings - кастомные настройки

Если в selenium вы получаете такую ошибку:

Fatal error: Uncaught Facebook\WebDriver\Exception\UnknownErrorException: unknown error: result.webdriverValue.value list is missing or empty in Runtime.callFunctionOn response

То скорее всего дело в том, что ваш браузер обновился и теперь не до конца соответствует выбранному драйверу. 

Либо обновите драйвер, либо скачайте chrome нужной версии. 

Сначала надо создать базу. Потом в баще надо выполнить запросы: 

CREATE EXTENSION postgis;
CREATE EXTENSION hstore;

Далее перейдем к самому импорту.

Пример команды с названиями:

"путь к osm2pgsql.exe" -c -d название_базы -U название_пользователя --password  -H localhost -S "путь до default.style" " путь до файла .osm.pbf"

Более реальный пример:

"C:\путь\osm2pgsql.exe" -c -d mydatabase -U postgres --password  -H localhost -S "C:\Users\путь\osm\default.style" "C:\Users\путь\osm\estonia-latest.osm.pbf"

Если osm2pgsql.exe прописать в path, тогда первый путь можно не указывать целиком, а указывать только osm2pgsql

--password нужен если у вашей базы есть пароль, затем после надо будет его ввести (в командной строке скрипт запросит об этом отбельно)

Рассмотрим случай, когда необходимо отследить, если вдруг внутри div поменялмя html код. 

Код-пример: 


var target = $('.testClass');

var observer = new MutationObserver(function(mutations) {
console.log(target.innerText);
});

observer.observe(target, {
attributes: true,
childList: true,
characterData: true
});

HTML:

<div class="testClass">test</div>

Как отслеживать, если у iframe поменялся атрибут src (on iframe src change)?

Пример кода:

 var iframeObserve = document.querySelector(".myiframe"),
observer = new MutationObserver((changes) => {
changes.forEach(change => {
if(change.attributeName.includes('src')){
alert('test');
}
});
});
observer.observe(iframeObserve, {attributes : true});

 

Сразу оговоримся - это только при условии что в iframe загружаются данные из-под этого же домена, иначе это будет невозможно.

Допустим, хотим узнать высоту div с классом class="mytest", который находится в iframe основной страницы.

Пример кода:

$(document).ready(function(){
$(".myiframe").on('load', function() {
var testdiv = $(this).contents().find(".mytest");
var height = testdiv.height();
console.log(height);
});
});

Первоначально надо дождаться, пока iframe загрузится, поэтому код обернут в on('load').

HTML:

<html>
<head>...</head>
<body>
...
<iframe class="myiframe">
....
<div class="mytest">test info</div>
</iframe>
</body>
</html>

В HTML сознательно пропущены куски кода, оставлены только основные моменты. 

Error LevelЗначениеОписание
E_ERROR1A fatal run-time error, that can't be recovered from. The execution of the script is stopped immediately.
E_WARNING2A run-time warning. It is non-fatal and most errors tend to fall into this category. The execution of the script is not stopped.
E_PARSE4The compile-time parse error. Parse errors should only be generated by the parser.
E_NOTICE8A run-time notice indicating that the script encountered something that could possibly an error, although the situation could also occur when running a script normally.
E_CORE_ERROR16A fatal error that occur during the PHP's engine initial startup. This is like an E_ERROR, except it is generated by the core of PHP.
E_CORE_WARNING32A non-fatal error that occur during the PHP's engine initial startup. This is like an E_WARNING, except it is generated by the core of PHP.
E_COMPILE_ERROR64A fatal error that occur while the script was being compiled. This is like an E_ERROR, except it is generated by the Zend Scripting Engine.
E_COMPILE_WARNING128A non-fatal error occur while the script was being compiled. This is like an E_WARNING, except it is generated by the Zend Scripting Engine.
E_USER_ERROR256A fatal user-generated error message. This is like an E_ERROR, except it is generated by the PHP code using the function trigger_error() rather than the PHP engine.
E_USER_WARNING512A non-fatal user-generated warning message. This is like an E_WARNING, except it is generated by the PHP code using the function trigger_error() rather than the PHP engine
E_USER_NOTICE1024A user-generated notice message. This is like an E_NOTICE, except it is generated by the PHP code using the function trigger_error() rather than the PHP engine.
E_STRICT2048Not strictly an error, but triggered whenever PHP encounters code that could lead to problems or forward incompatibilities
E_RECOVERABLE_ERROR4096A catchable fatal error. Although the error was fatal, it did not leave the PHP engine in an unstable state. If the error is not caught by a user defined error handler (see set_error_handler()), the application aborts as it was an E_ERROR.
E_DEPRECATED8192A run-time notice indicating that the code will not work in future versions of PHP
E_USER_DEPRECATED16384A user-generated warning message. This is like an E_DEPRECATED, except it is generated by the PHP code using the function trigger_error() rather than the PHP engine.
E_ALL32767All errors and warnings, except of level E_STRICT prior to PHP 5.4.0.

Если при работе с phpMyAdmin вы столкнулись с такой ошибкой: 

"Return type of Twig\Markup::count() should either be compatible with Countable::count(): int"

То один из самых простых способов ее исправить - это скрыть отображение deprecated в php.ini. В нашем случае (использовалось OSPanel / Open Server) это как раз помогло. 

Откройте файл настроек php.ini и пропишите: 

error_reporting              = E_ALL &  ~E_DEPRECATED

Ошибка обычно появляется при переходе на более новую версию PHP. 

Альтернатива - обновить phpMyAdmin. 

Что делать, если у вас появилась такая ошибка в MySQL:

Column count of mysql.user is wrong. Expected 45, found 43. 
Created with MySQL 50725, now running 50733.
Please use mysql_upgrade to fix this error.

Исправить ее достаточно просто. Выполните такую команду в командной строке: 

mysql_upgrade --force -uroot -p

Допустим после удаления некоторых элементов есть такой массив:

$test = array(
2 => "Test1",
10 => "Test2",
22 => "Test3"
);

Необходимо получить:

$test = array(
0 => "Test1",
1 => "Test2",
2 => "Test3"
);

Как этого добиться:

$result = array_values($test);
print_r($result); //выведет нужный результат

Если необходимо заменить много пробелов (любое количество) на один пробел в строке, то для этого можно воспользоваться регулярными выражениями.

Пример: 

$sourceString = ' a b   c  d e';
$result = preg_replace('!\s+!', ' ', $sourceString);
var_dump($result); //результат: " a b c d e"

Если в более новой версии PHP вы встретились с ошибкой “Fatal error: Array and string offset access syntax with curly braces is no longer supported”, то поправить ее будет очень просто.

Решение: 

заменить в строке ошибки фигурные скобки на квадратные

Пример: 

$myString = "podelitsa";

echo($myString{0}); //ошибка
echo($myString[0]); //решение

Возможна такая ситуация, когда при работе с Selenium возникла необходимость в отправке POST запроса. 

Основная проблема в том, что Selenium такие запросы не поддерживает.

Что же можно сделать? 

Есть одно решение: так как Selenium  позволяет выполнять на странице JavaScript, то с помощью скриптов можно динамически создать форму на странице и затем ее отправить. Либо же сразу сделать нужный вам запрос с помощью JavaScript.  

Простой вариант (PHP + JavaScript): 

$client = Client::createChromeClient();
$client->request('GET', 'mytest.com');
$js = '

let data = {elementName: "value"};
fetch('https://testaddress.com', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
}).then(res => {

console.log('Response:', res);

});
';
$client->executeScript($js);
$client->close();

В данном примере сначала открываем страницу mytest.com с помощью Selenium (Symfony Panther), затем отправляем POST запрос на testaddress.com используя js.