输出被提交多次

7

目前我正在使用simple_html_dom来爬取一个网站,点击此处查看我正在抓取的网站,所有内容都可以正常返回,除了它会为每个帖子持续放置相同的内容... 点击此处查看演示

$page = (isset($_GET['p'])&&$_GET['p']!=0) ? (int) $_GET['p'] : '';  
$html = file_get_html('http://screenrant.com/movie-news/'.$page);

foreach($html->find('#site-top > div.site-wrapper > div.top-content > article > section > ul > li > div.info > h2 > a') as $element)
{
    print '<br><br>';
    echo $url = ''.$element->href;
    $html2 = file_get_html($url);

    $image = $html2->find('meta[property=og:image]',0);
    $news['image'] = $image->content;
    #print '<br><br>';

    // Ending The Featured Image

    #site-top > div.site-wrapper > div.top-content > article > section > ul > li:nth-child(2)

    $title = $html2->find('#site-top > div.site-wrapper > div.top-content > article > header.single-header > h1',0);
    $news['title'] = $title->plaintext;

    // Ending the titles
    print '<br>';
    #site-top > div.site-wrapper > div.top-content > article > div
    $articles = $html2->find('#site-top > div.site-wrapper > div.top-content > article > div > p');
    foreach ($articles as $article) {
    #echo "$article->plaintext<p>"; 
    $news['content'] = $news['content'] . $article->plaintext . "<p>";
    }

    print '<pre>';print_r($news);print '</pre>';

    print '<br><br>';

        // mysqli_query($DB,"INSERT INTO `wp_scraped_news` SET
             //                   `hash` = '".$news['title']."',
               //                 `title` = '".$news['title']."',
                 //               `image` = '".$news['image']."',
                   //             `content` = '".$news['content']."'");
         // print '<pre>';print_r($news);print '</pre>';
}

我不知道我在这里做错了什么,但我认为有两件事情可能出了问题,并且我已经尝试过这两件事情,但没有成功。
1. 我在布置我的foreach时做错了一些事情。
2. 网站对于每篇新文章都在更改选择器。
在这两种情况下,我可能都错了...但是我已经尝试了两个小时,现在已经放弃了...非常感谢任何帮助。

我认为你选择的路径可能是错误的。在Chrome中,选择你想要的HTML元素,右键点击然后点击复制>复制选择器。我得到了类似于这样的东西:#site-top > div.site-wrapper > div.top-content > article > section > ul > li:nth-child(2) > div.info > div > div > p -- 可能需要将 li:nth-child(2) 更改为 li .. 这是一个开始的地方。 - Clay
3
@Clayton,如果你看一下所显示的代码,我已经注释掉了它,因为我已经尝试过了。- 只需再把那段代码放回去,它会返回仅在“新闻”归档页面上显示的片段,我们在顶部声明了URL,这意味着我们能够抓取内容页。 - Placeholder
1个回答

4
问题在于您没有清除$news['content']中的旧内容。因此,当您处理第二页时,您将其内容附加到第一页的内容中。第三页再次附加到此内容中,依此类推。
请添加以下代码:
$news['content'] = '';

之前

foreach ($articles as $article) {

仔细查看输出。它并没有为每篇文章显示相同的内容。开头是一样的,但是每次都会变长。 - Barmar
我肯定做错了...你能否编辑你的帖子,显示我应该如何做?因为将 $article['content'] = ''; 放在 foreach ($articles as $article) { 上面只会在第43行返回一个错误。 - Placeholder
抱歉,那是一个打字错误。应该是 $news['content'] = '';。这就是我在文本中说需要清除的变量。 - Barmar
你难道不觉得奇怪吗?我说你需要清除一个变量,但我的代码却说要清除另一个变量。如果你想一想,就会发现我犯了一个错误。 - Barmar
已经醒了20个小时左右,我现在不能很好地理解事情了。 - Placeholder
1
不要盲目地复制代码,要理解它。否则你就学不到东西。 - Barmar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接