亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

XPath 不檢索某些內容

XPath 不檢索某些內容

PHP
千萬里不及你 2022-07-29 16:26:38
我是一個新手,試圖編寫一個爬蟲來從論壇中獲取一些統計信息。這是我的代碼:<?php$ch = curl_init();$timeout = 0; // set to zero for no timeoutcurl_setopt ($ch, CURLOPT_URL, 'http://m.jeuxvideo.com/forums/42-51-61913988-1-0-1-0-je-code-un-bot-pour-le-forom-je-vous-le-montre-en-action.htm');curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);$file_contents = curl_exec($ch);curl_close($ch);$dom = new DOMDocument;libxml_use_internal_errors(true);$dom->loadHTML($file_contents);$xpath = new DOMXPath($dom);$posts = $xpath->query("//div[@class='who-post']/a");//$elements = $xpath->query("/html/body/div[@id='yourTagIdHere']");$dates = $xpath->query("//div[@class='date-post']");//$elements = $xpath->query("/html/body/div[@id='yourTagIdHere']");$contents = $xpath->query("//div[@class='message  text-enrichi-fmobile  text-crop-fmobile']/p");//$elements = $xpath->query("/html/body/div[@id='yourTagIdHere']");$i = 0;foreach ($posts as $post) {    $nodes = $post->childNodes;    foreach ($nodes as $node) {    $value = trim($node->nodeValue);      $tab[$i]['author'] = $value;      $i++;    }}$i = 0;foreach ($dates as $date) {    $nodes = $date->childNodes;    foreach ($nodes as $node) {      $value = trim($node->nodeValue);      $tab[$i]['date'] = $value;      $i++;    }}$i = 0;foreach ($contents as $content) {    $nodes = $content->childNodes;    foreach ($nodes as $node) {      $value = $node->nodeValue;      echo $value;        $tab[$i]['content'] = trim($value);        $i++;    }}?><h1>Participants</h2><pre><?php print_r($tab);?></pre>如您所見,代碼不會檢索某些內容。例如,我試圖從以下位置檢索此內容:http: //m.jeuxvideo.com/forums/42-51-61913988-1-0-1-0-je-code-un-bot-pour-le-forom -je-vous-le-montre-en-action.htm第二個帖子是一張圖片,我的代碼不起作用。另一方面,我想我犯了一些錯誤,我發現我的代碼很難看。你能幫我嗎 ?
查看完整描述

1 回答

?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

您可以簡單地先選擇帖子,然后使用以下方法分別獲取每個子數據:

代碼:

$xpath = new DOMXPath($dom);

$postsElements = $xpath->query('//*[@class="post"]');


$posts = [];

foreach ($postsElements as $postElement) {

  $author = $xpath->evaluate('normalize-space(.//*[@class="who-post"])', $postElement);

  $date = $xpath->evaluate('normalize-space(.//*[@class="date-post"])', $postElement);


  $message = '';

  foreach ($xpath->query('.//*[contains(@class, "message")]/p', $postElement) as $messageParagraphElement) {

    $message .= $dom->saveHTML($messageParagraphElement);

  }


  $posts[] = (object)compact('author', 'date', 'message');

}


print_r($posts);

無關說明:抓取網站的 HTML 本身并不違法,但您應避免在未經他們同意的情況下在您自己的應用程序/網站上顯示他們的數據。此外,如果他們決定更改其 HTML 結構/CSS 類名,這可能會在任何時候中斷。


查看完整回答
反對 回復 2022-07-29
  • 1 回答
  • 0 關注
  • 127 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號