樹莓派
上個月月末,入手了第一臺樹莓派函似。樹莓派是什么槐脏?沒有決定購買之前,只見過同事在玩撇寞,覺得很神奇顿天。研究后才知道這是一個微型電腦。
具體的就不在這里說了蔑担。到手之后折騰了兩天牌废,在樹莓派3b上搭建一套ubuntu系統(tǒng)。嗯啤握,這也是我第一次搭建和使用ubuntu鸟缕。
做什么呢
樹莓派到手了,用來做什么呢排抬?
一開始打算弄一弄深度學(xué)習(xí)懂从,嘗試了一下tensorflow和caffe,都失敗了蹲蒲,裝不上番甩。這套專為樹莓派使用的Ubuntu貌似有不少問題。
那就做點簡單的吧届搁,比如爬蟲缘薛。
之前做過的爬蟲是java版本的webmagic窍育,感覺不好用。這次打算嘗試一下python宴胧。反正國慶假期多漱抓,就趁機會把python也學(xué)習(xí)一下。
準備工作
python:
教程:http://www.runoob.com/python3/python3-tutorial.html
了解基本的語法恕齐,以及l(fā)inux下python的使用辽旋,包括版本切換、執(zhí)行python文件等檐迟。
Beautiful Soup:
教程:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
了解使用它獲取html內(nèi)容的相關(guān)方法。
MySQL-python
python連接mysql:http://www.cnblogs.com/fnng/p/3565912.html
爬什么內(nèi)容
在簡書搜了一下码耐,發(fā)現(xiàn)一個可以快速參考的文章:
http://www.reibang.com/p/be891e7e96e2
寫得比較詳細追迟,就決定依樣畫葫蘆爬簡書吧。
代碼實現(xiàn)
表結(jié)構(gòu):
/*
SQLyog Ultimate v12.4.3 (64 bit)
MySQL - 5.7.13-log : Database - scrapy_jianshu
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`scrapy_jianshu` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */;
USE `scrapy_jianshu`;
/*Table structure for table `jianshu_article` */
DROP TABLE IF EXISTS `jianshu_article`;
CREATE TABLE `jianshu_article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`article_type` varchar(30) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '文章分類',
`article_id` varchar(30) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '簡書上的文章id',
`title` varchar(150) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`author` varchar(30) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`author_id` varchar(30) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '作者id',
`abstract` text COLLATE utf8mb4_unicode_ci COMMENT '摘要',
`content` mediumtext COLLATE utf8mb4_unicode_ci,
`like_count` int(6) DEFAULT NULL COMMENT '點贊數(shù)',
`reward_count` int(4) DEFAULT NULL COMMENT '打賞數(shù)',
`comment_count` int(6) DEFAULT NULL COMMENT '評論數(shù)',
`link` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '文章鏈接',
`read_count` int(11) DEFAULT NULL COMMENT '閱讀量',
`create_time` datetime DEFAULT NULL COMMENT '發(fā)表時間',
PRIMARY KEY (`id`),
UNIQUE KEY `article_id` (`article_id`)
) ENGINE=InnoDB AUTO_INCREMENT=29782 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
python源碼:
#!/usr/bin/env python
#coding=utf-8
import requests
from bs4 import BeautifulSoup
import pymysql
from datetime import datetime
# 打開數(shù)據(jù)庫連接
db = pymysql.connect("192.168.0.102","root","root","scrapy_jianshu",charset="utf8")
# 使用 cursor() 方法創(chuàng)建一個游標(biāo)對象 cursor
cursor = db.cursor()
# MySQLdb正常情況下會嘗試將所有的內(nèi)容轉(zhuǎn)為latin1字符集處理骚腥,所以設(shè)置編碼如下
cursor.execute('SET NAMES utf8;')
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET character_set_connection=utf8;')
# 推薦分類
recommendations='http://www.reibang.com/recommendations/collections?page=%d&order_by=recommend'
# 簡書分類
base_urls=[]
# 抓取函數(shù)
def scrapy_artilce(url):
add_url=0
n=1000#每個專題抓取最受歡迎的前1000篇文章
while(n>0):
try:
add_url += 1
n = n-1
response=requests.request('get',url% add_url)
page=response.content
soup=BeautifulSoup(page,'html.parser')
type="'"+soup.select("a.name")[0].get_text() #文章分類
article_list = [article for article in soup.select("div.content")]
for article in article_list:
author=article.select("a.blue-link")[0].get_text()#文章作者
author_id=article.select("a.blue-link")[0].get('href')#作者id
title=article.select("a.title")[0].get_text()#文章標(biāo)題
article_id=article.select("a.title")[0].get('href')#文章id
abstract=article.select("p.abstract")[0].get_text()#文章摘要
link="http://www.reibang.com"+article_id#文章鏈接
# 抓取文章正文
response1=requests.request('get',link)
page1=response1.content
soup1=BeautifulSoup(page1,'html.parser')
content=''
if len(soup1.select('.show-content')):
content=soup1.select('.show-content')[0].get_text()#文章內(nèi)容
read=0 #文章閱讀量
if len(article.select(".ic-list-read")):
read=article.select(".ic-list-read")[0].find_parent().get_text() #文章閱讀量
read=int(read)
comment=0 #文章評論量
if len(article.select(".ic-list-comments")):
comment=article.select(".ic-list-comments")[0].find_parent().get_text() #文章評論量
comment=int(comment)
like=0 #文章點贊量
if len(article.select(".ic-list-like")):
like=article.select(".ic-list-like")[0].find_parent().get_text() #文章點贊量
like=int(like)
reward=0 #文章贊賞數(shù)量
if len(article.select(".ic-list-money")):
reward=article.select(".ic-list-money")[0].find_parent().get_text() #文章贊賞數(shù)量
reward=int(reward)
create_time=article.select(".time")[0].get('data-shared-at')#發(fā)表時間
create_time=create_time.replace('T',' ')
create_time=create_time.replace('+08:00','')
create_time=datetime.strptime(create_time,"%Y-%m-%d %H:%M:%S")
sql="insert into jianshu_article (title,article_id,article_type,author,author_id,abstract,like_count,reward_count,comment_count,link,read_count,content,create_time) \
values ('%s','%s',%s','%s','%s','%s','%d','%d','%d','%s','%d','%s','%s')" % \
(title,article_id,type,author,author_id,abstract,like,reward,comment,link,read,content,create_time)
try:
cursor.execute(sql)
db.commit()
except Exception as e:
print('錯誤sql:'+sql)
print(e)
db.rollback()
except Exception as e:
print(e)
# 開始抓取
add_url=1
while(add_url<50):#推薦專題沒有超過50個
try:
response=requests.request('get',recommendations% add_url)
page=response.content
soup=BeautifulSoup(page,'html.parser')
tyle_list=[_type for _type in soup.select("div.collection-wrap")]
for _type in tyle_list:
_type_id=_type.select(".avatar-collection")[0].find_parent().get('href')
type_link='http://www.reibang.com'+_type_id+'?order_by=top&page=%d'
base_urls.append(type_link)
add_url +=1
except Exception as e:
print(e)
for _type in base_urls:
scrapy_artilce(_type)
# 關(guān)閉數(shù)據(jù)庫連接
db.close()
總結(jié)
這個簡單的爬蟲在樹莓派上跑了將近兩天敦间,按照各個專題內(nèi)文章的點贊數(shù)排序,已經(jīng)抓取了7w+文章束铭。
樹莓派的好處是便宜廓块,200多塊錢就可以搭建好的一臺linux服務(wù)器,而且耗電少契沫,持續(xù)運行也不怎么發(fā)熱带猴。
后來又想爬心聲論壇的內(nèi)容,于是就又寫了一個簡單點的:
#!/usr/bin/env python
#coding=utf-8
import requests
from bs4 import BeautifulSoup
import pymysql
from datetime import datetime
import re
# 打開數(shù)據(jù)庫連接
db = pymysql.connect("192.168.0.102","root","root","scrapy_jianshu",charset="utf8")
# 使用 cursor() 方法創(chuàng)建一個游標(biāo)對象 cursor
cursor = db.cursor()
# MySQLdb正常情況下會嘗試將所有的內(nèi)容轉(zhuǎn)為latin1字符集處理懈万,所以設(shè)置編碼如下
cursor.execute('SET NAMES utf8;')
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET character_set_connection=utf8;')
# 按點擊最多排序
xinsheng_base_url='http://xinsheng.huawei.com/cn/index.php?app=forum&mod=List&act=index&class=461&order=viewcount&type=&sign=&special=&p=%d'
# 抓取函數(shù)
def scrapy_artilce(url):
add_url=0
while(True):
try:
add_url += 1
response=requests.request('get',url% add_url)
page=response.content
soup=BeautifulSoup(page,'html.parser')
type="'"+'' #文章分類
article_list = [article for article in soup.select("div.font_box")]
for article in article_list:
author=article.select(".pro")[0].select("a")[0].get_text()#文章作者
if len(article.select(".space_rz_blue")):
author=article.select(".space_rz_blue")[0].find_parent().get_text()#文章作者
author=author.replace(' ','')
author_id=''#作者id
title=article.select("p")[0].select('font')[0].select('a')[0].get_text()#文章標(biāo)題
article_id=''#文章id
abstract=''#文章摘要
link=article.select("p")[0].select('font')[0].select('a')[0].get('href')#文章鏈接
# 抓取文章正文
response1=requests.request('get',link)
page1=response1.content
soup1=BeautifulSoup(page1,'html.parser')
content=''
if len(soup1.select('.bbs_info_right_text')):
content=soup1.select('.bbs_info_right_text')[0].get_text()#文章內(nèi)容
if len(content) == 0:
content=soup1.select('.bbs_info_right_text')[1].get_text()
read=0 #文章閱讀量
comment=0 #文章評論量
if len(article.select('.pro_width')):
read=article.select('.pro_width')[0].get_text() #文章閱讀量
if len(article.select('.iconReply')):
comment=article.select('.iconReply')[0].find_parent().get_text() #文章評論量
read=int(read)
comment=int(comment)
like=0 #文章點贊量
reward=0 #文章贊賞數(shù)量
create_time='1970-01-01'
if len(article.select('.pro')):
create_time=article.select('.pro')[0].get_text()#發(fā)表時間
create_time= re.findall(r"\d{4}-\d{2}-\d{2}",create_time)[0]
create_time=datetime.strptime(create_time,"%Y-%m-%d")
sql="insert into xinsheng_article (title,article_id,article_type,author,author_id,abstract,like_count,reward_count,comment_count,link,read_count,content,create_time) \
values ('%s','%s',%s','%s','%s','%s','%d','%d','%d','%s','%d','%s','%s')" % \
(title,article_id,type,author,author_id,abstract,like,reward,comment,link,read,content,create_time)
#print(sql)
try:
cursor.execute(sql)
db.commit()
except Exception as e:
print('錯誤sql:'+sql)
print(e)
db.rollback()
except Exception as e:
print(e)
# 開始抓取
scrapy_artilce(xinsheng_base_url)
# 關(guān)閉數(shù)據(jù)庫連接
db.close()
到目前為止拴清,也已經(jīng)從心聲論壇上抓取到了4w+文章。后續(xù)可以在這些數(shù)據(jù)的基礎(chǔ)之上做一些查詢和分析了会通。