The Dormouse's story
Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well.
...
""" 上面的 *爱丽丝* 文档经过 Beautiful Soup 的解析后,会得到一个 :py:class:`BeautifulSoup` 的对象, 一个嵌套结构的对象: :: from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc, 'html.parser') print(soup.prettify()) # # ## # The Dormouse's story # #
## Once upon a time there were three little sisters; and their names were # # Elsie # # , # # Lacie # # and # # Tillie # # ; and they lived at the bottom of a well. #
## ... #
# # 这是几个简单的浏览结构化数据的方法: :: soup.title #The Dormouse's story
soup.p['class'] # u'title' soup.a # Elsie soup.find_all('a') # [Elsie, # Lacie, # Tillie] soup.find(id="link3") # Tillie 常见任务之一,就是从文档中找到所有 标签的链接: :: for link in soup.find_all('a'): print(link.get('href')) # http://example.com/elsie # http://example.com/lacie # http://example.com/tillie 另一种常见任务,是从文档中获取所有文字内容: :: print(soup.get_text()) # The Dormouse's story # # The Dormouse's story # # Once upon a time there were three little sisters; and their names were # Elsie, # Lacie and # Tillie; # and they lived at the bottom of a well. # # ... 这是你想要的吗?是的话,继续看下去。 安装 Beautiful Soup ====================== 如果你用的是新版的 Debain 或 Ubuntu,那么可以通过系统的软件包管理来安装: :kbd:`$ apt-get install python3-bs4` Beautiful Soup 4 通过 PyPi 发布,所以如果无法使用系统包管理安装,那么 也可以通过 ``easy_install`` 或 ``pip`` 来安装。包的名字是 ``beautifulsoup4``。 确保使用的是与 Python 版本对应的 ``pip`` 或 ``easy_install`` 版本 (他们的名字也可能是 ``pip3`` 和 ``easy_install`` )。 :kbd:`$ easy_install beautifulsoup4` :kbd:`$ pip install beautifulsoup4` (在 PyPi 中还有一个名字是 ``BeautifulSoup`` 的包,但那可能不是你想要的,那是 `Beautiful Soup3`_ 版本。因为很多项目还在使用BS3, 所以 ``BeautifulSoup`` 包依然有效。但是新项目中,应该安装 ``beautifulsoup4``。) 如果没有安装 ``easy_install`` 或 ``pip`` ,那也可以 `下载 BS4 的源码Extremely bold.. py:attribute:: attrs 一个 HTML 或 XML 的 tag 可能有很多属性。tag ```` 有 一个 "id" 的属性,值为 "boldest"。你可以想处理一个字段一样来处理 tag 的属性: :: tag = BeautifulSoup('bold', 'html.parser').b tag['id'] # 'boldest' 也可以直接"点"取属性,比如: ``.attrs`` : :: tag.attrs # {u'class': u'boldest'} tag 的属性可以被添加、删除或修改。再说一次,tag的属性操作方法与字典一样 :: tag['id'] = 'verybold' tag['another-attribute'] = 1 tag # del tag['id'] del tag['another-attribute'] tag # bold tag['id'] # KeyError: 'id' tag.get('id') # None .. _multivalue: 多值属性 ---------- HTML 4 定义了一系列可以包含多个值的属性。在 HTML5 中移除了一些,却增加更多。 最常见的多值的属性是 ``class`` (一个 tag 可以有多个 CSS class)。还有一些 属性 ``rel``、 ``rev``、 ``accept-charset``、 ``headers``、 ``accesskey``。 默认情况,Beautiful Soup 中将多值属性解析为一个列表: :: css_soup = BeautifulSoup('', 'html.parser') css_soup.p['class'] # ['body'] css_soup = BeautifulSoup('', 'html.parser') css_soup.p['class'] # ['body', 'strikeout'] If an attribute `looks` like it has more than one value, but it's not a multi-valued attribute as defined by any version of the HTML standard, Beautiful Soup will leave the attribute alone:: id_soup = BeautifulSoup('', 'html.parser') id_soup.p['id'] # 'my id' 如果某个属性看起来好像有多个值,但在任何版本的 HTML 定义中都没有将其定义为多值属性, 那么 Beautiful Soup 会将这个属性作为单值返回 :: id_soup = BeautifulSoup('', 'html.parser') id_soup.p['id'] # 'my id' 将 tag 转换成字符串时,多值属性会合并为一个值 :: rel_soup = BeautifulSoup('
Back to the homepage
', 'html.parser') rel_soup.a['rel'] # ['index', 'first'] rel_soup.a['rel'] = ['index', 'contents'] print(rel_soup.p) #Back to the homepage
若想强制将所有属性当做多值进行解析,可以在 :py:class:`BeautifulSoup` 构造方法中设置 ``multi_valued_attributes=None`` 参数: :: no_list_soup = BeautifulSoup('', 'html.parser', multi_valued_attributes=None) no_list_soup.p['class'] # 'body strikeout' 或者使用 ``get_attribute_list`` 方法来获取多值列表,不管是不是一个多值属性: :: id_soup.p.get_attribute_list('id') # ["my id"] 如果以 XML 方式解析文档,则没有多值属性: :: xml_soup = BeautifulSoup('', 'xml') xml_soup.p['class'] # 'body strikeout' 但是,可以通过配置 ``multi_valued_attributes`` 参数来修改: :: class_is_multi= { '*' : 'class'} xml_soup = BeautifulSoup('', 'xml', multi_valued_attributes=class_is_multi) xml_soup.p['class'] # ['body', 'strikeout'] 可能实际当中并不需要修改默认配置,默认采用的是 HTML 标准: :: from bs4.builder import builder_registry builder_registry.lookup('html').DEFAULT_CDATA_LIST_ATTRIBUTES .. py:class:: NavigableString 可遍历的字符串 ---------------- 字符串对应 tag 中的一段文本。Beautiful Soup 用 :py:class:`NavigableString` 类来包装 tag 中的字符串: :: soup = BeautifulSoup('Extremely bold', 'html.parser') tag = soup.b tag.string # 'Extremely bold' type(tag.string) #No longer bold:py:class:`NavigableString` 对象支持 `遍历文档树`_ 和 `搜索文档树`_ 中定义的大部分属性, 并非全部。尤其是,一个字符串不能包含其它内容(tag 能够包含字符串或是其它 tag),字符串不支持 ``.contents`` 或 ``.string`` 属性或 ``find()`` 方法。 如果想在 Beautiful Soup 之外使用 :py:class:`NavigableString` 对象,需要调用 ``unicode()`` 方法,将该对象转换成普通的Unicode字符串,否则就算 Beautiful Soup 方法已经执行结束,该对象的输出 也会带有对象的引用地址。这样会浪费内存。 .. py:class:: BeautifulSoup ------------------------------- ``BeautifulSoup`` 对象表示的是一个文档的全部内容。大部分时候,可以把它当作 ``Tag`` 对象, 它支持 `遍历文档树`_ 和 `搜索文档树`_ 中描述的大部分的方法。 因为 ``BeautifulSoup`` 对象并不是真正的HTML或XML的tag,所以它没有name和attribute属性。 但有时查看它的 ``.name`` 属性是很方便的,所以 ``BeautifulSoup`` 对象包含了一个 值为 "[document]" 的特殊属性 ``.name`` :: soup.name # u'[document]' 注释及特殊字符串 ----------------- :py:class:`Tag`, :py:class:`NavigableString`, :py:class:`BeautifulSoup` 几乎覆盖了html和xml中的所有内容,但是还有一些特殊对象。容易让人担心的内容是文档的注释部分: :: markup = "" soup = BeautifulSoup(markup, 'html.parser') comment = soup.b.string type(comment) #