简单的Python爬虫-就是这么简单

前言:

这段时间断断续续在学Python,觉得爬虫很有意思,想把一些心得记录下来,不足之处很多,大家随便看看。本人用到的是urllib2和正则的方式,爬取首页的文章列表,并存储到sqlite3中。

1. 开发工具和用到的库

  • Python下载:本人暂时用的2.x版本,下载地址点这里
  • 编辑器下载:本人用的是PyCharm Community
  • 用到的库有:urllib2、re和sqlite3。

2. 开始写代码

 import re    
 import urllib2
 import sqlite3

导入正则库,url请求库以及Python自带的sqlite3数据库。正则表达式的学习可以参考这里。

  • 获取网页内容
url = "http://www.jianshu.com"
req = urllib2.urlopen(url)
buf = req.read().decode('utf-8')
print buf

这样我们就获取到了网页内容。为了告诉服务器我们不是爬虫,可以加上header:

url = 'http://www.jianshu.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

有些网站是post请求,所以还要添加参数:

#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
  • 解析网页,获取文章列表。我只要了文章列表的作者,时间,标题,简介,分类,阅读数,评论数,收藏数和打赏数。
简单的Python爬虫-就是这么简单_第1张图片
屏幕快照 2017-09-22 下午2.17.20.png
pattern = re.compile('(.*?)'+'.*?'
            +'.*?(.*?)'+'.*?(.*?)

'+ '.*?(.*?)'+ '.*?(.*?)'+'.*?(.*?)'+'.*?(.*?)',re.S|re.M) items = re.findall(pattern,buf)

.*? 非贪婪模式,忽略掉那些不要的内容
(.
?) 分组,获取到你需要的内容
re.S 使 . 匹配包括换行在内的所有字符
re.M 多行匹配,影响 ^ 和 $

  • 最后保存到 sqlite3数据库中
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创建表
id INTEGER primary key AUTOINCREMENT主键自动增加
c.executemany('INSERT INTO articelList VALUES(NULL,?,?,?,?,?,?,?,?)',list)把文章列表数据插入表中

3. 完整代码:

# 抓取首页
def getContent():
    try:
        str1 = 'http://www.jianshu.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('(.*?)'+'.*?'
            +'.*?(.*?)'+'.*?(.*?)

'+ '.*?(.*?)'+ '.*?(.*?)'+'.*?(.*?)'+'.*?(.*?)'+ '.*?.*?(.*?)',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 # 存入数据库 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()

运行结果:

简单的Python爬虫-就是这么简单_第2张图片
屏幕快照 2017-09-22 下午2.42.00.png

你可能感兴趣的:(简单的Python爬虫-就是这么简单)