美文网首页
爬虫入门(四):urllib2

爬虫入门(四):urllib2

作者: 朴有天虹 | 来源:发表于2017-06-06 15:25 被阅读0次

date: 2016-10-14 20:42:22

主要使用python自带的urllib2进行爬虫实验。

写在前面的蠢事:
本来新建了一个urllib2.py便于好认识这是urllib2的实验,结果始终编译不通过,错误错误。不能用Python的关键字(保留字)来命名py文件,改了就好了。

正则表达式与re

Python 通过 re 模块提供对正则表达式的支持。使用 re 的一般步骤是:
Step1:先将正则表达式的字符串形式编译为Pattern实例。
Step2:然后使用Pattern实例处理文本并获得匹配结果(一个Match实例)。
Step3:最后使用Match实例获得信息,进行其他的操作。
<pre>

!/usr/bin/env python

-- coding: utf-8 --

@Date : 2016-10-14 21:16:25

@Author : Nicolo (1241251168@qq.com)

@Link : http://www.xiaosablog.cf/

@Version : $Id$

一个简单的re实例,匹配字符串中的hello字符串

导入re模块

import re

将正则表达式编译成Pattern对象,注意hello前面的r的意思是“原生字符串”

pattern = re.compile(r'hello')

使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None

match1 = pattern.match('hello world!')
match2 = pattern.match('helloo world!')
match3 = pattern.match('helllo world!')

如果match1匹配成功

if match1:

使用Match获得分组信息

print match1.group()

else:
print 'match1匹配失败!'

如果match2匹配成功

if match2:

使用Match获得分组信息

print match2.group()

else:
print 'match2匹配失败!'

如果match3匹配成功

if match3:

使用Match获得分组信息

print match3.group()

else:
print 'match3匹配失败!'

</pre>

编译结果:

<pre>
hello
hello
match3匹配失败!
</pre>

糗事百科的网络爬虫

<pre>
import urllib2
import urllib
import re
import thread
import time

----------- 加载处理糗事百科 -----------

class Spider_Model:

def __init__(self):    
    self.page = 1    
    self.pages = []    
    self.enable = False    

# 将所有的段子都扣出来,添加到列表中并且返回列表    
def GetPage(self,page):    
    myUrl = "http://m.qiushibaike.com/hot/page/" + page    
    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'   
    headers = { 'User-Agent' : user_agent }   
    req = urllib2.Request(myUrl, headers = headers)   
    myResponse = urllib2.urlopen(req)  
    myPage = myResponse.read()    
    #encode的作用是将unicode编码转换成其他编码的字符串    
    #decode的作用是将其他编码的字符串转换成unicode编码    
    unicodePage = myPage.decode("utf-8")    

    # 找出所有class="content"的div标记    
    #re.S是任意匹配模式,也就是.可以匹配换行符    
    myItems = re.findall('<div.*?class="content".*?title="(.*?)">(.*?)</div>',unicodePage,re.S)    
    items = []    
    for item in myItems:    
        # item 中第一个是div的标题,也就是时间    
        # item 中第二个是div的内容,也就是内容    
        items.append([item[0].replace("\n",""),item[1].replace("\n","")])    
    return items    

# 用于加载新的段子    
def LoadPage(self):    
    # 如果用户未输入quit则一直运行    
    while self.enable:    
        # 如果pages数组中的内容小于2个    
        if len(self.pages) < 2:    
            try:    
                # 获取新的页面中的段子们    
                myPage = self.GetPage(str(self.page))    
                self.page += 1    
                self.pages.append(myPage)    
            except:    
                print '无法链接糗事百科!'    
        else:    
            time.sleep(1)    
        
def ShowPage(self,nowPage,page):    
    for items in nowPage:    
        print u'第%d页' % page , items[0]  , items[1]    
        myInput = raw_input()    
        if myInput == "quit":    
            self.enable = False    
            break    
        
def Start(self):    
    self.enable = True    
    page = self.page    

    print u'正在加载中请稍候......'    
        
    # 新建一个线程在后台加载段子并存储    
    thread.start_new_thread(self.LoadPage,())    
        
    #----------- 加载处理糗事百科 -----------    
    while self.enable:    
        # 如果self的page数组中存有元素    
        if self.pages:    
            nowPage = self.pages[0]    
            del self.pages[0]    
            self.ShowPage(nowPage,page)    
            page += 1    

----------- 程序的入口处 -----------

print u"""

程序:糗百爬虫
操作:输入quit退出阅读糗事百科
功能:按下回车依次浏览今日的糗百热点


"""

print u'请按下回车浏览今日的糗百内容:'
raw_input(' ')
myModel = Spider_Model()
myModel.Start()
</pre>

相关文章

网友评论

      本文标题:爬虫入门(四):urllib2

      本文链接:https://www.haomeiwen.com/subject/vxagfxtx.html