使用PHP网络搜寻器查找没有某些元素的某些单词

时间:2019-03-19 17:23:57

标签: javascript php html web-scraping web-crawler

我遵循http://simplehtmldom.sourceforge.net/使用php制作网络抓取工具,但是我很困惑如何在不指定元素的情况下搜索单词。因此,单词搜索是基于所有可用数据进行的。 因为这里的问题是现在我要使用<p>元素指定要搜索的数据,但是当没有元素<p>时结果为空。

这是我的代码

<?php
include "simple_html_dom.php";
$html = file_get_html('https://adityadees.blogspot.com/');

foreach($html->find('<p>') as $element) 
if (strpos($element, 'yang') !== false) {
    echo $element;
} else {
    echo $element;
}
?>
例如,

我想尝试搜索包含'yang'的单词,但是结果为空,因为这些单词不包含

元素。 enter image description here

我的结果 enter image description here

,但是如果单词包含在

元素中,则结果会很好。 enter image description here

我会尝试更改此行

foreach($html->find('<p>') as $element) 

foreach($html->find() as $element) 

但是我遇到这样的错误

  

致命错误:未捕获的ArgumentCountError:的参数太少   函数simple_html_dom :: find(),传入0   第5行的C:\ xampp \ htdocs \ crawl \ index.php,预计至少有1个   C:\ xampp \ htdocs \ crawl \ simple_html_dom.php:1975堆栈跟踪:#0   C:\ xampp \ htdocs \ crawl \ index.php(5):simple_html_dom-> find()#1 {main}   1975年在C:\ xampp \ htdocs \ crawl \ simple_html_dom.php中抛出

3 个答案:

答案 0 :(得分:1)

您要查找包含给定单词的所有段落/文本吗?

<?php 
include('simple_html_dom.php');

$html = file_get_html('https://adityadees.blogspot.com/');

$strings_array = array();

//it searches for any (*) tag with text yang in it
foreach($html->find('*[plaintext*=yang]') as $element) {
    //take only elements which doesn't have childnodes, so are last ones in recursion 
    if ($element->firstChild() == null) {
        //there still are duplicate strings so add only unique values to an array
        if (!in_array($element->innertext, $strings_array)) {
            $strings_array[] = $element->innertext;

        }
    } 
}

echo '<pre>';
print_r($strings_array);
echo '</pre>';

?>

这不是最终的解决方案,而是一些开始。 至少找到61个单词yang-与给定页面的html源相同。

答案 1 :(得分:0)

怎么样:

foreach($html->find('<body>') as $element) 
if (strpos($element, 'yang') !== false) {
    echo $element;
} else {
    echo $element;
}

答案 2 :(得分:0)

检查给定页面的源代码后,您可以看到帖子摘要位于div标签中,类为=项目代码片段。

<div class='item-snippet'> Bagaimana Cara Mengganti Akun Mobile Legend ?  itulah yang selalu dipertanyakan oleh orang yang baru memulai bermain game Mobile Legend.  S...</div>

如果您在这样的div中搜索单词,就可以得到结果:

include('simple_html_dom.php');

$html = file_get_html('https://adityadees.blogspot.com/');

foreach($html->find('div[class=item-snippet]') as $element) {

    if (strpos($element, 'yang') !== false) {

        echo $element;

    } 

}

结果:

Bagaimana Cara Mengganti Akun Mobile Legend ? itulah yang selalu dipertanyakan oleh orang yang baru memulai bermain game Mobile Legend. S...
Bagaimana Cara Mengaitkan Akun Mobile Legend di Patch Baru ? Mungkin masih ada yang bingung tentang cara mengaitkan akun mobile legend den...
Kali ini kita akan membahas tentang bagaimana cara menghitung luas persegi panjangan dengan PHP Hal yang pertama dilakukan adalah membuat ...

您要寻找的吗?