zoukankan      html  css  js  c++  java
  • python爬虫 ----文章爬虫(合理处理字符串中的 ........)

    import urllib.request
    import re
    import time
    
    num=input("输入日期(20150101000):")
    
    
    
    def openpage(url):
        html=urllib.request.urlopen(url)
        
        page=html.read().decode('gb2312')
        
        return page
    
    def getpassage(page):
        passage = re.findall(r'<p class="MsoNormal" align="left">([sS]*)</FONT>',str(page))
        
        passage1=re.sub("</?w+[^>]*>", "", str(passage))
        
        passage2=passage1.replace('\r', '
    ').replace('\n', ' 
    ').replace('\t','	').replace(']','').replace('[','').replace('&nbsp;','   ')
    
        print(passage2)
    
        with open(load,'a',encoding='utf-8') as f:
            f.write("-----------------------------"+"日期"+str(date)+"---------------------------------
    "+passage2+"----------------------------------------------------
    ")
    
    
    
    
    
    for i in range(1,32):
        date=int(num)+int(i)
        print(date)
        load="C:/Users/home/Desktop/新建文本文档.txt"
        url=("http://www.hbuas.edu.cn/news/xyxw/news_"+str(date)+".htm")
        
      
    try: page=openpage(url) getpassage(page) print(""+str(i)+"号有文章,----已下载") except: print(""+str(i)+"号无文章。") time.sleep(2)

    写了一个爬学校新闻网的爬虫,

    主要涉及   re正则   urllib.request   文件的写入  

    在爬取文章时通常会返回很多影响美感的代码

     如下:

     优化:

    两次正则    

    passage = re.findall(r'<p align="left">([sS]*)</FONT>',str(page))       #第一次匹配字段
        
    passage1=re.sub("</?w+[^>]*>", "", str(passage))              # 第二次去掉html标签

    替换

    passage2=passage1.replace('\r', '
    ').replace('\n', ' 
    ').replace('\t','	').replace(']','').replace('[','').replace('&nbsp;','   ')

    效果如下:

    over!

  • 相关阅读:
    大数据技术栈,主要有哪些
    微服务海量日志监控平台
    Elastic APM安装
    Elasticsearch SSL认证/证书制作
    Elastic APM 上报数据分析与应用
    elasticsearch7.X x-pack破解
    Netty源码学习系列之5-NioEventLoop的run方法
    Netty源码学习系列之4-ServerBootstrap的bind方法
    Netty源码学习系列之3-ServerBootstrap的初始化
    Netty源码学习系列之2-NioEventLoopGroup的初始化
  • 原文地址:https://www.cnblogs.com/jjj-fly/p/7351017.html
Copyright © 2011-2022 走看看