zoukankan      html  css  js  c++  java
  • 提取网易的链接及链接名称 分类: python 小练习 正则表达式 2013-11-07 14:02 382人阅读 评论(0) 收藏

    import urllib2,re
    
    #读取网页信息
    def getcontent(url):
        request=urllib2.Request(url)
        f=urllib2.urlopen(request)
        content= f.read()
        return content
    
    #使用re提取所需信息
    def pars_content(url):
        content = getcontent(url)
        p=re.compile('<a.*?href="(.*?)"(.*?")?>(.*?)<')
    ##    print p.search(content).groups(2,3)
        result=p.findall(content)
        for link,middle,text in result:
            print link,'-->',text
    
    pars_content("http://www.163.com")
    
    '''
    url测试数据:
    
    <a class="ntes-nav-entry-wide c-fl" target="_self" href="http://www.163.com/" onclick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://www.163.com/');" title="把网易设为首页">设为首页</a>
    <a href="http://reg.163.com/" class="ntes-nav-login-title">登录</a>
    <ahref="http://reg.163.com/" class="ntes-nav-login-title">登录</a>
    <a href="http://m.163.com/newsapp/#f=topnav"><span><em class="ntes-nav-app-newsapp">网易新闻</em></span></a></li>
    <a href="http://m.163.com/#f=topnav" class="ntes-nav-select-title ntes-nav-entry-bgblack JS_NTES_LOG_FE" data-module-name="n_topnavapp">应用<em class="ntes-nav-select-arr"></em></a>
    <a href="http://news.163.com/special/i/000117JD/index_history.html">历史回顾</a>
    
    
    正则解释:
    
    .*? 用于 匹配a 与href 之间的内容,如空格、制表符,其他字符等
    href=" 匹配该字符串后面内容
    (.*?) 对href="后面的内容放入组1中
    (.*?")?> 匹配链接后面的内容,如第5条测试数据中的<span><em class="ntes-nav-app-newsapp">,该匹配出现0或1次
    (.*?)< 匹配链接名称,该链接名称后面是<
    '''


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    开发DBA(APPLICATION DBA)的重要性
    SQL有外连接的时候注意过滤条件位置
    程序与bug
    Dalvik虚拟机进程和线程的创建过程分析
    Dalvik虚拟机简要介绍和学习计划
    Dalvik虚拟机的运行过程分析
    JRE和JDK的概念
    myeclipse6.0.1(内置了eclipse)安装及其配置
    JDK 环境变量如何设置
    jdk1.5和tomcat5.5免安装的环境配置
  • 原文地址:https://www.cnblogs.com/think1988/p/4628026.html
Copyright © 2011-2022 走看看