bs4 库

Python bs4库

  • bs4库简介
  • 安装方法
  • 使用方法
    • 导包
    • 获取内容或文件
    • 获取html标签属性及文本
    • 实例
  • 如有错误,请指正

bs4库简介

BeautifulSoup库是解析、遍历、维护标签树代码的功能库;名字为beautifulsoup4,简称bs4

安装方法

pip install beautifulsoup4

使用方法

导包

from bs4 import BeautifulSoup

获取内容或文件

html = BeautifulSoup(test, 'html.parser') #获取网页内容

获取html标签属性及文本

语法

	某某.p 	#获取html下的第一个p标签
	某某.body.div.a	#顺着节点找到a标签
	某某.p.parent.name #找p标签的父元素标签
	某某.find_all('p') #获取html下的所有p标签
	某某.find(class='p1') #获取class为p1的标签

实例

from bs4 import BeautifulSoup #导包

#网页内容
test = """




Study


    
	

java

python

c

c++ html html css """ #获取网页内容 html = BeautifulSoup(test, 'html.parser')

获取html下的第一个p标签

p = html.p
print(p)

结果:

python

找p标签的父元素标签

p = html.p.parent.name
print(p)

结果:body

顺着节点找到a标签

#顺着节点找到a标签
a = html.body.div.a
print(a)

结果:taopais

获取第一个p标签中的class属性值

p = html.p['class']
print()

结果:['p1']

获取html下所有p标签

p = html.find_all('p')
print(p)

结果:[

python

,

c

]

获取id为p1的标签

p = html.find(id='p1') 
print(p)

结果:

python

强调一下find 和 find_all 可以有多个搜索条件叠加,比如

find('p', id='p1', class_='pp')
class使用时需要加上下横杠,因为class在python中也存在

如有错误,请指正

@taopad

你可能感兴趣的:(爬虫,python,html,爬虫)