前言:
這段時間斷斷續(xù)續(xù)在學Python,覺得爬蟲很有意思,想把一些心得記錄下來,不足之處很多,大家隨便看看。本人用到的是urllib2和正則的方式,爬取簡書首頁的文章列表,并存儲到sqlite3中。
1. 開發(fā)工具和用到的庫
- Python下載:本人暫時用的2.x版本,下載地址點這里
- 編輯器下載:本人用的是PyCharm Community
- 用到的庫有:urllib2、re和sqlite3。
2. 開始寫代碼
import re
import urllib2
import sqlite3
導入正則庫,url請求庫以及Python自帶的sqlite3數(shù)據(jù)庫。正則表達式的學習可以參考這里。
- 獲取網(wǎng)頁內(nèi)容
url = "http://www.lxweimin.com"
req = urllib2.urlopen(url)
buf = req.read().decode('utf-8')
print buf
這樣我們就獲取到了網(wǎng)頁內(nèi)容。為了告訴服務器我們不是爬蟲,可以加上header:
url = 'http://www.lxweimin.com'
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36')
req = urllib2.urlopen(request)
buf = req.read().decode('utf-8')
print buf
有些網(wǎng)站是post請求,所以還要添加參數(shù):
#post請求需要添加urllib庫
import urllib
str1 = 'http://xxxx'
params = {'key':'value','key':'value'}
data = urllib.urlencode(params)
request = urllib2.Request(str1,data=data)
req = urllib2.urlopen(request)
buf = req.read()
print buf
- 解析網(wǎng)頁,獲取文章列表。我只要了文章列表的作者,時間,標題,簡介,分類,閱讀數(shù),評論數(shù),收藏數(shù)和打賞數(shù)。
屏幕快照 2017-09-22 下午2.17.20.png
pattern = re.compile('<a.*?blue-link.*?>(.*?)</a>'+'.*?<span.*?data-shared-at="(.*?)">'
+'.*?<a.*?title.*?>(.*?)</a>'+'.*?<p.*?>(.*?)</p>'+
'.*?<a.*?collection-tag.*?>(.*?)</a>'+
'.*?</i>(.*?)</a>'+'.*?</i>(.*?)</a>'+'.*?</i>(.*?)</span>',re.S|re.M)
items = re.findall(pattern,buf)
.*? 非貪婪模式,忽略掉那些不要的內(nèi)容
(.?) 分組,獲取到你需要的內(nèi)容
re.S 使 . 匹配包括換行在內(nèi)的所有字符
re.M 多行匹配,影響 ^ 和 $
- 最后保存到 sqlite3數(shù)據(jù)庫中
def saveJianShuContent(list):
coon=sqlite3.connect("jianshu.db")
c = coon.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS articelList(id INTEGER primary key AUTOINCREMENT,name text,time text,title text,content text
,tag text,read text,commond text,love text)''')
c.executemany('INSERT INTO articelList VALUES(NULL,?,?,?,?,?,?,?,?)',list)
coon.commit()
coon.close()
coon=sqlite3.connect("jianshu.db")
如果沒有jianshu.db那么它會自動生成
c = coon.cursor()
獲取游標
c.execute
創(chuàng)建表
id INTEGER primary key AUTOINCREMENT
主鍵自動增加
c.executemany('INSERT INTO articelList VALUES(NULL,?,?,?,?,?,?,?,?)',list)
把文章列表數(shù)據(jù)插入表中
3. 完整代碼:
# 抓取簡書首頁
def getContent():
try:
str1 = 'http://www.lxweimin.com'
request = urllib2.Request(str1)
request.add_header('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36')
req = urllib2.urlopen(request)
buf = req.read().decode('utf-8')
pattern = re.compile('<a.*?blue-link.*?>(.*?)</a>'+'.*?<span.*?data-shared-at="(.*?)">'
+'.*?<a.*?title.*?>(.*?)</a>'+'.*?<p.*?>(.*?)</p>'+
'.*?<a.*?collection-tag.*?>(.*?)</a>'+
'.*?</i>(.*?)</a>'+'.*?</i>(.*?)</a>'+'.*?</i>(.*?)</span>'+
'.*?<span>.*?</i>(.*?)</span>',re.S|re.M)
items = re.findall(pattern,buf)
saveJianShuContent(items)
for item in items:
for item1 in items:
print 'name---'+item1[0].encode('utf-8'),'time---'+item1[1],\
'title---'+ item1[2].encode('utf-8'),'content---'+item1[3].encode('utf-8'),\
'tag---'+item1[4].encode('utf-8'),'read--'+item1[5].encode('utf-8'),\
'commond--'+item1[6].encode('utf-8'),'collect--'+item1[7].encode('utf-8'),'money---'+item1[8].encode('utf-8')
except url.URLError, e:
if hasattr(e,"code"):
print e.code
if hasattr(e,"reason"):
print e.reason
# 存入數(shù)據(jù)庫
def saveJianShuContent(list):
coon= sqlite3.connect("jianshu.db")
c = coon.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS articelList(id INTEGER primary key AUTOINCREMENT,name text,time text,title text,content text
,tag text,read text,commond text,love text,moeny text)''')
c.executemany('INSERT INTO articelList VALUES(NULL,?,?,?,?,?,?,?,?,?)',list)
coon.commit()
coon.close()
if __name__ == '__main__':
getContent()
運行結果:
屏幕快照 2017-09-22 下午2.42.00.png