BeautifulSoup随笔

BeautifulSoup是一个类

b = BeautifulSoup(html)

b对象有与html结构相关的各种方法和和属性。

a = b.findAll('a')获得标签的对象

a对象又有关于属性的各种方法和属性吧

获取某网页的所有连接:

from bs4 import BeautifulSoup
import urllib.request
import sys

url = 'http://news.163.com/'

#获取网页html
html = urllib.request.urlopen(url).read()
html = html.decode('gbk')

#通过BeautifulSoup提取href
a = BeautifulSoup(html).findAll('a')
count = 0
err_a_list = []
for i in a:
    try:
        if i and i.attrs['href'][0] != 'j':  #排除href = java..
            print(i.attrs['href'])
    except Exception as e:            #当没有href属性或属性值为空时会报错,捕获以防止循环被中断
        print(e)
        err_a_list.append(i)
        count += 1
print("\n"*8)
for i in err_a_list:
    print(i)
    print()
print(count)

 

对网址没有域名以及锚点等href处理:

 http://blog.csdn.net/huangxiongbiao/article/details/45584407

    # 将形如#comment-text的锚点补全成http://www.ruanyifeng.com/blog/2015/05/co.html,将形如/feed.html补全为http://www.ruanyifeng.com/feed.html
    alist = map(lambda i: proto + '://' + domain + i if i[0] == '/' else url + i if i[0] == '#' else i, alist)

 

s

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值