3.BeautifulSoup对象的初始化
- 初始化方法
第一步:从bs4库导入BeautifulSoup模块
from bs4 import BeautifulSoup
第二步:实例化BeautifulSoup对象
soup = BeautifulSoup(html,'lxml')
第一个参数为要解析的文档字符串
第二个参数为解析器类型(这里用lxml)
- 将这个对象赋值给soup变量
- 实例化后会把不完整的HTML文档字符串自动更正为标准的HTML字符串,如下实例:
html ="""
<html>
<head>
<title>The Dormouse's story</title>
</heads>
<body>
<p class="title" name="dromouse">cb>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><1-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">lacie</a> and
<a href-"http://example.com/tillie" class="sister" id-"link3">Tillie </a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup)
- 上述文档是一个不标准的html字符串,经过实例化后自动更正,输出结果如下:
<html>
<head>
<title>The Dormouse's story</title>
</head><body>
<p class="title" name="dromouse">cb>The Dormouse's story</p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a class="sister" href="http://example.com/elsie" id="link1"><1-- Elsie --></a>,
<a class="sister" href="http://example.com/lacie" id="link2">lacie</a> and
<a class="sister" href-="" id-="">Tillie </a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
</body></html>
心揣信念,梦想就在脚下!

浙公网安备 33010602011771号