###前提・実現したいこと
WordPressでウェブスクレイピングを行おうとしています。
https://teratail.com/questions/97951 で
表示している表示している固定ページごとに情報を抽出するURLの変更を行う方法を回答していただきました。
今回はその続きになります。
やりたいこと
ページの中に抽出したいものが複数あり
抽出したものを固定ぺージに表示
例:
URL1のサイトからid名〜id名4のテキストを取得
↓
ショートコードを利用して固定ぺージに表示
※抽出元のHTMLは例とは別でそれぞれ若干違います。
###該当のソースコード URL1のサイト <ul> <li> <h2></h2> <p><span id="id名"></span><br><span id="id名2"></span></p> </li> <li><p id="id名3"></p></li> <li id="id名4"></li> </ul> URL2のサイト <ul> <li> <h2></h2> <p><span id="id名"></span><br><span id="id名2"></span></p> </li> <li><p id="id名3"></p></li> <li id="id名4"></li> </ul> URL3のサイト <ul> <li> <h2></h2> <p><span id="id名"></span><br><span id="id名2"></span></p> </li> <li><p id="id名3"></p></li> <li id="id名4"></li> </ul>
WordPressのfunction.phpに記載してるもの function shortcode() { require_once("phpQuery-onefile.php"); if(is_page('1')){ //固定ページ1だった場合は$htmlにURL1のサイトを $html = file_get_contents("URL1"); }elseif(is_page('2')){ $html = file_get_contents("URL2"); //固定ページ2だった場合は$htmlにURL2のサイトを }else{ $html = file_get_contents("URL3"); //その他の場合は$htmlにURL3のサイトを } return phpQuery::newDocument($html)->find("#id名")->text(); } add_shortcode('shortcode1', 'shortcode'); id名〜id名4のショートコードを利用したい。
###ay03様からいただいた回答の以下部分の処理をまとめたい
require_once("phpQuery-onefile.php");
if(is_page('1')){
$html = file_get_contents("URL1");
}elseif(is_page('2')){
$html = file_get_contents("URL2");
}else{
$html = file_get_contents("URL3");
}
$id1 = phpQuery::newDocument($html)->find("#id名1")->text();
return $id1;
###試したこと
function htmlurl($id, $htmlid) {
require_once("phpQuery-onefile.php");
if(is_page('1')){
$html = file_get_contents("URL1");
}elseif(is_page('2')){
$html = file_get_contents("URL2");
}else{
$html = file_get_contents("3");
}
$id = phpQuery::newDocument($html)->find($htmlid)->text();
return $id;
}
htmlurl('$id1', '#id名1');
function shortcode1() {
global $id1;
return $id1;
}
add_shortcode('shortcode1', 'shortcode1');
htmlurl('$id2', '#id名2');
function shortcode2() {
global $id2;
return $id2;
}
add_shortcode('shortcode2', 'shortcode2');
htmlurl('$id3', '#id名3');
function shortcode3() {
global $id3;
return $id3;
}
add_shortcode('shortcode3', 'shortcode3');
htmlurl('$id4', '#id名4');
function shortcode4() {
global $id4;
return $id4;
}
add_shortcode('shortcode4', 'shortcode4');
結果 空白
回答1件
あなたの回答
tips
プレビュー