外观
解析HTML代码
解析HTML代码包含获取标题、获取指定标签内容等。
要解析 HTML 代码,首先需要导入 bs4 模块,因为 BeautifulSoup 已经被内置在了其中。然后,我们需要安装解析器 lxml。接下来,我们可以从其他网页获取 HTML 代码,然后将其传递给 BeautifulSoup 对象进行解析。
例:
import requests
from bs4 import BeautifulSoup
url = 'https://www.baidu.com'
response = requests.get(url).content
result = BeautifulSoup(response, features='lxml')
print('此网站的标题是: ', result.title)
# 还可以解析本地HTML代码
# file = open('demo.html', encoding='utf8')
# result = BeautifulSoup(file, 'lxml')
# print(result.prettify()) # prettify()方法会把代码格式化
# print(result.find('meta')) # find()方法返回参数要求的html内容运行结果:
此网站的标题是: <title>百度一下,你就知道</title>