- Почему Simple HTML DOM не находит отдельные объекты?
- 1 ответ 1
- Почему simple_html_dom не работает с некоторыми сайтами?
- 3 ответа 3
- Всё ещё ищете ответ? Посмотрите другие вопросы с метками php парсер или задайте свой вопрос.
- Связанные
- Похожие
- Подписаться на ленту
- Not compatible with php 7.3 #64
- Comments
- vistart commented Dec 13, 2018
- oza75 commented Dec 15, 2018
- wotupset commented Dec 16, 2018
- ArniPL commented Dec 17, 2018
- ArniPL commented Dec 17, 2018
- Kub-AT commented Jan 3, 2019
- luigitek commented Apr 10, 2019 •
- Kub-AT commented Apr 11, 2019
- luigitek commented Apr 11, 2019
- derryberni commented Apr 13, 2019
- Kub-AT commented Apr 15, 2019
- PHP Simple HTML DOM Parser
- A php based DOM parser.
- Brought to you by: john_schlick, logmanoriginal, me578022
- Searches
- #108 html->find error
- Discussion
- PHP Simple HTML DOM Parser
- A php based DOM parser.
- Brought to you by: john_schlick, logmanoriginal, me578022
- Searches
- #42 Fatal error in simple_html_dom::find()
- Discussion
Почему Simple HTML DOM не находит отдельные объекты?
Добрый день, подскажите пожалуйста. Столкнулся со следующей проблемой. Пытаюсь парсить следующую страницу: http://superdeals.aliexpress.com/en
Необходимо достать div который хранится в li с class list-items. Однако получается так, что далеко не все данные отображаются на странице. Код выглядит следующим образом:
То есть Simple HTML DOM даже не видит отдельные части страницы, исполнение кода = пустой странице, ставлю дургой div — все работает. Если парсить всю страницу file_get_html, то естественным образом отображается далеко не весь сайт. Подскажите пожалуйста как можно обойти проблему.
Заранее спасибо большое!
1 ответ 1
Кроме голого HTML на странице есть скрипты, которые догружают данные с сервера. Содержимое div.pro-msg заполняется одним из скриптов.
Беглый осмотр показал, что нужно смотреть на SuperdealSingle.getSingleData() . В этой функции происходит заполнение шаблона после запроса к серверу с адресом типа http://api.dos.aliexpress.com/aliexpress/data/doQuery.jsonp. . Запросы к данной странице не блокируются и вроде не имеют никакой привязки к авторизации. Вы можете брать параметры для запроса после парсинга HTML, потом обращаться к вышеуказанному адресу с нужными значениями и получать нужные вам данные в виде JSONP.
Например вот что получаем при соответствующем запросе (добавлено форматирование кода):
Здесь видны все необходимые вам данные.
Если возникнут проблемы, придется более глубоко покопаться в скриптах.
Источник
Почему simple_html_dom не работает с некоторыми сайтами?
Добрый вечер. simple_html_dom не работает с некоторыми сайтами, например world-art.ru и kinopoisk.ru, почему так?
По идее, должен вывести все картинки и ссылки с страницы. Но вместо этого — пустая страница.
3 ответа 3
Причина, скорее всего, в коде этих сайтов. DOM- и XML-парсеры требуют валидности разметки для правильного разбора.
Ну www.world-art.ru защищается. Сделайте
Увидите пустоту. Выход — закачивать страницы через curl эмулируя браузеры.
Только добавьте нужные опции. Ну или используйте другие парсеры, которые умеют это из коробки
simple_html_dom работает только с UTF-8. Если пихать в неё страницы в Windows-1251 — будете получать пустоту.
Всё ещё ищете ответ? Посмотрите другие вопросы с метками php парсер или задайте свой вопрос.
Связанные
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.10.19.40496
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Источник
Not compatible with php 7.3 #64
Comments
vistart commented Dec 13, 2018
PHP Warning ‘yii\base\ErrorException’ with message ‘preg_match(): Compilation failed: invalid range in character class at offset 4’
The text was updated successfully, but these errors were encountered:
oza75 commented Dec 15, 2018
I got the same error
wotupset commented Dec 16, 2018
php 7.3 has some bugs in preg_* function
ArniPL commented Dec 17, 2018
@wotupset Not bugs. PHP 7.3 has updated its regular expression engine to PCRE2, which brings some breaking changes.
I think the dash in referenced expression needs to be escaped.
ArniPL commented Dec 17, 2018
There’s even a PR opened two months ago that fixes this: #63 but it’s left unmerged. This package might be abandoned.
Kub-AT commented Jan 3, 2019
Author of original PHP Simple HTML DOM Parser (sourceforge hosted) did an update on 2018-12-10 (after 6 year ;)) version 1.7 is compatible with PHP 7.3
https://sourceforge.net/projects/simplehtmldom/files/simplehtmldom/1.7/
luigitek commented Apr 10, 2019 •
This version doesn’t work as expected for example:
The above fails if the div has more than 1 class. I’m currently working with version 1.7.1 which doesn’t have this issue.
Kub-AT commented Apr 11, 2019
This version doesn’t work as expected for example:
The above fails if the div has more than 1 class. I’m currently working with version 1.7.1 which doesn’t have this issue.
It would be nice if you reported a bug here https://sourceforge.net/p/simplehtmldom/bugs/
luigitek commented Apr 11, 2019
careful with 1.8.1 which is the version used by https://github.com/Kub-AT/php-simple-html-dom-parser
This version doesn’t work as expected for example:
$dom->find(‘div[class=name]’, 0);
The above fails if the div has more than 1 class. I’m currently working with version 1.7.1 which doesn’t have this issue.
I’ll include more details to it as soon as I get a chance 👍
derryberni commented Apr 13, 2019
Author of original PHP Simple HTML DOM Parser (sourceforge hosted) did an update on 2018-12-10 (after 6 year ;)) version 1.7 is compatible with PHP 7.3
https://sourceforge.net/projects/simplehtmldom/files/simplehtmldom/1.7/
but i get error
Message: Call to undefined method KubAT\PhpSimple\HtmlDomParser::loadFromUrl()
Kub-AT commented Apr 15, 2019
7.3 compatible version:
https://github.com/Kub-AT/php-simple-html-dom-parser
Author of original PHP Simple HTML DOM Parser (sourceforge hosted) did an update on 2018-12-10 (after 6 year ;)) version 1.7 is compatible with PHP 7.3
https://sourceforge.net/projects/simplehtmldom/files/simplehtmldom/1.7/
but i get error
Message: Call to undefined method KubAT\PhpSimple\HtmlDomParser::loadFromUrl()
Источник
PHP Simple HTML DOM Parser
A php based DOM parser.
Brought to you by: john_schlick, logmanoriginal, me578022
Searches
#108 html->find error
When I run the example php script I get an error: Fatal error: Call to a member function find() on a non-object in /mnt/133/sda/0/9/nigelstrang59/htmltry.php on line 6 — it seems to be saying that $html is not an object .
here is the code (almost a copy paste from sourceforge) — any ideas?
find(\’a\’);
echo $ret;
?>
Discussion
please note the \ preceding the » are not present in the code
This fatal error usually appears when trying to use null or something else as an object, iow using the -> to call a method.
Chances are that for whatever reason file_get_html returned null or false, should verify this. To take simple_html_dom completely out of the equation see if you are able to fetch the url with file_get_contents().
Please let us know what you find, if you still don’t have any luck may I ask that you give a more detailed report including version numbers and step by step process so that someone may reproduce the fault.
I did your example without the escaped string quotes and it worked.
You could also try:
$html = new simple_html_dom();
$dom = $html->load_file(‘http://www.google.com/’);
if (!empty($dom))
$dom->find(‘a’);
Also try something other than google not always the friendliest approach for your first attempts as you are very likely to by confronted by several 3xx responses which you’d need to deal with.
Hi Nick i am using object oriented method and it is working on my development server. But the problem is that it is not working on live server. Both servers have same configuration.
I am getting this error on my live server:
PHP Fatal error: Call to a member function find() on a non-object in tmp_scripts/simple_html_dom.php on line 1113
I am using following code :
$html = $html = new simple_html_dom();
$url = «http://www.hotels.com/hotel/details.html?tab=description&hotelId=».$id.»&arrivalDate=08-29-13&departureDate=08-30-13&rooms [0] .numberOfAdults=1&roomno=1&validate=false&previousDateful=false&reviewOrder=date_newest_first#reviews»;
$html->load_file($url);
$count = count($html->find(‘div.review’));
if($count > 0) <
foreach($html->find(‘div.review’) as $data ) <
>
>
$id can contain 243147,141744
on dev server when I am using 243147.. it is retrieving the 0 count (as it should) and getting data for second values.
but on live server I am getting fatal error.
I also tried ur code (that is getting load_file in variable and then accessing other methods using that). In that case I am not getting error. but also not getting any data.
Источник
PHP Simple HTML DOM Parser
A php based DOM parser.
Brought to you by: john_schlick, logmanoriginal, me578022
Searches
#42 Fatal error in simple_html_dom::find()
Fatal error in simple_html_dom::find():
«Call to a member function find() on a non-object»
This error happened quite often to me, when spidering lots of websites in a loop.
I was not able to pinpoint the problem to a specific website/URL in order to reproduce the problem, but added the following line of code in order to no longer end up with PHP-Fatal-errors:
Proposed solution:
if (! is_object($this->root))
return null;
Problematic Code-Function:
simple_html_dom::find()
Problematic Code-Line:
return $this->root->find($selector, $idx);
Discussion
I am stuck due to this problem in the middle of on project. I am spidering among many urls and fetching in the loop. However, after the first URL parsed the second time that function is called where i am parsing the page i get this error.
I would really appreciate if you could help me identify where to patch your proposed code.
Below is my code/function which is parsing a page and I have to call this function repeatedly for different URLs
================================================================
function getBusinessList($url,$statecode) <
$businessInfoList = array();
//$html = null;
// tags
$rank = »; $businessname = »; $pageurl = »; $street = »; $city = »;
$state = »; $zip = »; $mainphone = »; $website = »;
Comment has been marked as spam.
View and moderate all «bugs Discussion» comments posted by this user
The code below is working just well for me.
I make a little fix for this error
The problem is when the class use error_get_last() to check if load_file() worked and another script before simple_html_dom throw an error and set error_get_last() with their error, so, we need check if error_get_last() is generated from simple_html_dom class or not, so just an if sentence will fix this.
Источник