使用PHP Web爬虫查找某些没有特定元素的单词

问题描述 投票:2回答:3

我正在关注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'的单词,但结果为空,因为这些单词不包含<p>元素。 enter image description here

我的结果enter image description here

但如果单词包含在<p>元素中,结果就会很好。 enter image description here

我正试图改变这条线

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

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

但我得到这样的错误

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

javascript php html web-scraping web-crawler
3个回答
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次单词 - 与给定页面的html源相同。


0
投票

怎么样:

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

0
投票

在检查给定页面的来源后,您可以看到帖子摘要位于带有class = item-snippet的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 ...

这是你在找?

© www.soinside.com 2019 - 2024. All rights reserved.