標籤:style blog http color 資料 io 2014 html
在上篇 基於PHP採集資料入庫程式(二) 中提到採集新聞資訊頁的列表資料,接下來講講關於採集新聞具體內容
這是上篇部落格的最終資料表:
接下來要做的操作就是從資料庫中讀取所需要採集的URL,進行頁面抓取就行
建立一個content表
不過需要注意的一點是,不能再採用採集URL這種id遞增的方法去採集,因為資料表中可能出現id斷續,比如id=9,id=11,當採集到id=10的時候,URL是空白的,這樣可能會導致採集到了空欄位。
這裡用到的一個技巧是資料庫的查詢語句,在我們採集完第一條資料的時候,判斷資料庫裡是否還有大於此id的id編號,若有,讀取一條,查詢資訊重複上面的工作。
具體代碼如下:
<?php include_once("conn.php"); $id=(int)$_GET[‘id‘]; $sql="select * from list where id=$id"; $result=mysql_query($sql); $row=mysql_fetch_array($result);//取得對應的url地址 $content=file_get_contents($row[‘url‘]); $pattern="/<dd class=\"dataWrap\">(.*)<\/dd>/iUs"; preg_match($pattern, $content,$info);//擷取內容存放info echo $title=$row[1]."<br/>"; echo $content=$info[0]."<hr/>"; //插入資料庫 $add="insert into content(title,content) value(‘$title‘,‘$content‘)"; mysql_query($add); $sql2="select * from list where id>$id order by id asc limit 1"; $result2=mysql_query($sql2); $row2=mysql_fetch_array($result2);//取得對應的url地址 if($row2[‘id‘]){ echo "<script>window.location=‘content.php?id=$row2[0]‘</script>"; }?>
這樣子我們所要的新聞內容就採集入庫了,接下來只需要對資料的一些樣式進行整理就行了。