Beautiful Soup库的简单使用

一、BeautifulSoup库的简单使用

import requests
r=requests.get("http://python123.io/ws/demo.html")
demo=r.text
from bs4 import BeautifulSoup  #导入BeautifulSoup库
soup=BeautifulSoup(demo,"html.parser")  #使用html.parser进行解析
print(soup.prettify())  #打印解析结果

BeautifulSoup对应一个HTML/XML文档的全部内容

BeautifulSoup===标签树===BeautifulSoup类

二、BeautifulSoup标签的简单使用

使用下述.name,.attrs等访问名称,属性等:

基于bs4库的HTML内容遍历方法:

简单代码:

import requests
r=requests.get("http://python123.io/ws/demo.html")
demo=r.text
from bs4 import BeautifulSoup  #导入BeautifulSoup库
soup=BeautifulSoup(demo,"html.parser")  #使用html.parser进行解析
print(soup.title)  #若有多个类似标签,仅返回第一个
print(soup.a)
print(soup.a.name)   #返回名字
print(soup.a.parent.name)

tag=soup.a
print(tag.attrs)   #属性
print(tag.attrs['class'])
print(tag.string)   #两个尖括号之间的内容
print(type(tag.string))

print(soup.head)
print(soup.head.contents)   #contents返回其儿子

print(soup.title.parent)  #返回父节点

三、基于bs4库的HTML内容查找方法

如:

soup.find_all(string='Basic Python')
soup.find_all(id=re.compile('link'))   #正则表达式的模糊查询

扩展方法:

发布了462 篇原创文章 · 获赞 55 · 访问量 32万+

猜你喜欢

转载自blog.csdn.net/LY_624/article/details/105149023