提取网易的链接及链接名称 分类: python 小练习 ...

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/" οnclick="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次
(.*?)< 匹配链接名称,该链接名称后面是<
'''


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

转载于:https://www.cnblogs.com/think1988/p/4628026.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值