zoukankan      html  css  js  c++  java
  • Python爬虫之利用正则表达式爬取内涵吧

    首先,我们来看一下,爬虫前基本的知识点概括

    一. match()方法:

    这个方法会从字符串的开头去匹配(也可以指定开始的位置),如果在开始没有找到,立即返回None,匹配到一个结果,就不再匹配。

    我们可以指定开始的位置的索引是3,范围是3-10,那么python将从第4个字符'1'开始匹配,只匹配一个结果。

    group()获得一个或多个分组的字符串,指定多个字符串时将以元组的形式返回,group(0)代表整个匹配的字串,不填写参数时,group()返回的是group(0)。

     1 import re
     2 
     3 pattern = re.compile(r'd+')     #匹配数字一次以上
     4 m = pattern.match('one123two456')
     5 print m
     6 print m.group()
     7 
     8 #None
     9 #...AttributeError: 'NoneType' object has no attribute 'group'
    10 
    11 
    12 pattern = re.compile(r'd+')     #匹配数字一次以上
    13 m = pattern.match('one123two456'. 3, 10)
    14 print m
    15 print m.group()
    16 
    17 #<_sre.SRE_Match object at 0x00000000026FAE68>
    18 #123

    二. search()方法:

    search方法与match比较类似,区别在于match()方法只检测是不是在字符串的开始位置匹配,search()会扫描整个字符串查找匹配,同样,search方法只匹配一次。

    1 import re
    2 
    3 pattern = re.compile(r'd+')
    4 m = pattern.search('one123two456')
    5 print m.group()
    6 
    7 #123

    三. findall()方法:

    搜索字符串,以列表的形式返回全部能匹配的字串。

    1 import re
    2 
    3 pattern = re.compile(r'd+')
    4 m = pattern.findall('one123two456')
    5 print m
    6 
    7 #['123', '456']

    四. sub()方法:

    用来替换每一个匹配的字符串,并返回替换后的字符串。

    1 import re
    2 
    3 pattern = re.compile(r'd+')
    4 m = pattern.sub('abc', 'one123two456')
    5 print m
    6 
    7 #oneabctwo456

    五. 实践:爬取内涵吧段子

     1 #-*-coding:utf-8-*-
     2 
     3 import requests
     4 import re
     5 
     6 class Spider:
     7 
     8     def __init__(self):
     9         self.page = 1
    10 
    11     def getPage(self, page):
    12         url = "http://www.neihan8.com/article/list_5_{}.html".format(page)
    13         response = requests.get(url)
    14         contents =  response.content.decode('gbk')   #查看网页源代码,内涵吧默认编码是charset=gb2312
    15         return contents
    16 
    17     def getContent(self):
    18         contents = self.getPage(self.page) 
    19         pattern = re.compile('<h4>.*?<a href.*?html">(.*?)</a>.*?class="f18 mb20">(.*?)</div>', re.S)
    20         results = pattern.findall(contents)
    21         contents = []
    22         for item in results:
    23             title = re.sub('<b>|</b>', "", item[0])
    24             content = re.sub(r'<p>|</p>|<br />|&w+;|<img alt.*|<div style=.*>|<div>|<p style="text-align: center; ">', "", item[1])
    25             content = re.sub(r'<div class="upload-txt.*baseline;">|<h1 class="title".*vertical-align: baseline;">|</h1>', "", content)
    26             content = re.sub(r'<div class=.*onclick="showAnswer(this)">|</a><div class="answer">', "", content)
    27             content = re.sub(r'<span style="color: rgb.*;">', "", content)
    28             contents.append([title, content])
    29         return contents
    30 
    31     def save_Data(self):
    32         file = open("duanzi.txt", "w+")
    33         x = 1
    34         y = 1
    35         for self.page in range(0, 507):
    36             contents = self.getContent()
    37             print u"正在写入第%d页的数据..." %(self.page+1)
    38             for item in contents:
    39                 file.write(str(x) + "." + item[0])
    40                 file.write("
    ")
    41                 file.write(item[1])
    42                 file.write("=====================================================================================
    
    ")
    43                 if item==contents[-1]:
    44                     file.write(u"********第" + str(y) + "页完********
    
    ")
    45                     y += 1
    46                 x += 1            
    47         print u"所有页面已加载完"
    48 
    49     def start(self):
    50         self.save_Data()
    51                 
    52                              
    53 spider = Spider()
    54 spider.start()

    基本上可以获取段子的标题和内容,但由于内涵吧的段子越到后面标签越复杂,所以给替换标签带来了很大的难度。

  • 相关阅读:
    使用CDN后,PHP如何获取用户的真是IP?
    git常用命令整理
    svn常用命令
    Ansible 运维自动化(一)
    grep 简单笔记
    sed 笔记
    awk命令笔记
    无限极分类(一)获得树结构
    php自定义函数求取平方根
    class path resource [config.xml] cannot be opened because it does not exist
  • 原文地址:https://www.cnblogs.com/my_captain/p/7469179.html
Copyright © 2011-2022 走看看