python bs4模块属性方法

BeautifulSoup对象表示的是一个文档的全部内容。

一. 可以通过点属性的方式获取tag标签,通过点属性的方式只能获取当前名字的第一个tag

# -*-coding:utf-8 -*-

import urllib2
import chardet

from bs4 import BeautifulSoup

re = urllib2.Request('https://www.baidu.com')

response = urllib2.urlopen(re)

print "查看响应信息类型: %s" % type(response)

page = response.read()
print "内容编码格式:%s" % chardet.detect(page)
print(page.decode('utf-8'))

soup = BeautifulSoup(page, features="html.parser")
ht = soup.body
print ("string:", ht.get_text())
print ("string:", ht.string)
print ("name:", ht.name)
print ("text:", ht.text)
print ("contents:", ht.contents)
print ("attrs:", ht.attrs)
for item in soup.descendants:
    print item.name

属性:

1. 获取标签内容

get_text()、text、string,内容为空时,string获取到的是None

2.获取标签名

name

3.获取表现属性/获取属性值

attrs、ht["class"]

4. 返回一个列表,可继续获取子节点

contents

5.返回一个生成器,获取子节点

descedamts

6.select选择器

select()

二、可以通过搜索方法搜索文档树

方法:常用的两个方法为find()、find_all()、findAll() =find_all()

可以通过搜索方法搜索文档树
find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)

只返回第一个找到的标签

find(self, name=None, attrs={}, recursive=True, text=None, **kwargs)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值