0
0

More than 1 year has passed since last update.

ワードプレスでwebスクレイピング を使って自動投稿するプログラム

Last updated at Posted at 2022-05-07

自分で色々と開発した機能の保存メモとして残しています。

機能概要

・好きなURLの記事一覧から記事情報を取得して、各下層ページ記事のタイトル&内容も取得する。
・取得した各記事をワードプレスの投稿に入れる(公開or下書き)
・これをcronで時間指定をする
・最後に同じ記事の情報は取得しない。

環境

WordPress 5.9.3
PHP7.4.25

※思いつきで作ったコードです。

変数名など適当なのでぜひ変えて使ってください。

//スクレイピング関数
//aタグそのまま使えるバージョン
  function my_cron_function()
  {

	  //DB情報
$dsn='mysql:host=ホスト名;dbname=データベース名;charset=utf8';
$user='データベースユーザー名';
$password='パスワード';
	  

	  //スクレイピング用phpQuery読み込み
require_once( __DIR__ ."/phpQuery-onefile.php");
$home = "取得するURLのTOPドメイン";//トップURL
$html = file_get_contents("情報を取得するURLを指定");
$urls = phpQuery::newDocument($html)[".archive > .archive__item > .archive__contents > h2 > a"];

	  
$pdo = new PDO($dsn,$user,$password,[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);//dbに接続する
$f_sql = "CREATE TABLE if not exists `scrap_meta` ( `scrap_id` INT(11) AUTO_INCREMENT PRIMARY KEY, `scrap_url` VARCHAR(255) NOT NULL) charset=utf8 ENGINE = InnoDB";//もし無ければテーブルの作成
	  
$sql = "SELECT COUNT(*) FROM scrap_meta WHERE scrap_url = ? ";//レコードにあるかカウント
$sql2 = "INSERT INTO `scrap_meta` (`scrap_id`, `scrap_url`) VALUES (?,?) ";//レコードに挿入
	  
	  //最初はテーブルの作成
	  $pdo->query($f_sql);
	  
	  foreach ($urls as $url) {
		  $null = NULL;
		  $s_url = pq($url)->attr("href");
		  		  
		  $stmt = $pdo->prepare($sql);
		  $stmt->bindValue(1,$s_url);
		  $stmt->execute();
		  $count = $stmt->fetchColumn();
		  
		  if($count == 0){//カウントしてURLがレコードになければ
  $pq_url[] = $s_url;//URLをそれぞれ配列に格納
			  $stmt2 = $pdo->prepare($sql2);
			  $stmt2->bindValue(1,$null);
			  $stmt2->bindValue(2,$s_url);
			  $stmt2->execute();//取得したURLをレコードに挿入
		  }
}
	  
	  
	  if(isset($pq_url)){//$pq_urlがセットされていれば実行
		  	  
	  foreach ($pq_url as $k_url) {//下層URLでforeachする
		  sleep(5);// 連続実行するとサーバー負荷かかりすぎる5秒待機
  $pq_title[] = pq(phpQuery::newDocument(file_get_contents($k_url))[".dividerBottom > h1"])->text();//下層記事のタイトル
  $pq_content[] = pq(phpQuery::newDocument(file_get_contents($k_url))[".postContents > section "])->html();
}
	  
	  $pq_query = array_combine($pq_title,$pq_content);//配列の結合
	  
	  foreach ($pq_query as $key => $val) {
				   
              $my_postquery = array(
				  'post_title' =>$key,
				  'post_content'  => $val,
				  'post_status'   => 'draft',
				  'post_category' => array(7)//カテゴリー指定
			  );
             // 投稿をデータベースへ追加
             wp_insert_post( $my_postquery );
  }
  }
  }

  if (getenv('CRON') == 'ランダムな文字列' ) {//cronの値が'ランダムな文字列'なら実行
my_cron_function();
}

自分で設定をする部分①

$urls = phpQuery::newDocument($html)[".archive > .archive__item > .archive__contents > h2 > a"];

取得するhtmlのタグを指定していきます。

自分で設定をする部分②

$pq_title[] = pq(phpQuery::newDocument(file_get_contents($k_url))[".dividerBottom > h1"])->text();//下層記事のタイトル
$pq_content[] = pq(phpQuery::newDocument(file_get_contents($k_url))[".postContents > section "])->html();
}

取得するhtmlのタグを指定の方法

例えば以下のようなhtmlがあったとします。

<div class="header">
 <ul>
  <li class="list1"><a href="https://sample.com">テストURL</a></li>
  <li class="list2"></li>
  <li class="list3"></li>
 </ul>
</div>

ここで https://sample.com を取得したい場合は

["header > ul > .list1 > a"]

こんな感じで指定します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0