如何创建BeautifulSoup对象?
时间: 2024-01-29 07:04:55 浏览: 25
创建BeautifulSoup对象的步骤如下:
1. 导入BeautifulSoup库:`from bs4 import BeautifulSoup`
2. 读取HTML文件或HTML字符串,例如:`html_doc = "<html><head><title>The Dormouse's story</title></head><body><p class='title'><b>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'>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>"`
3. 创建BeautifulSoup对象:`soup = BeautifulSoup(html_doc, 'html.parser')`
其中,第二个参数指定解析器,这里使用的是Python内置的解析器html.parser。