BeautifulSoup

HTML说到底还是XML标记语言,因此解析XML在爬虫抓取结果后,对数据进行拆解分析,变少不了BeautifulSoup4了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
~/code/algorithm via algorithm 
➜ cat bf4.py
#!/bin/env python3
from bs4 import BeautifulSoup

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>
"""
soup = BeautifulSoup(html_doc, 'lxml')
print(soup.prettify())%

~/code/algorithm via algorithm
➜ python bf4.py

<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>

Traceback (most recent call last):
File "bf4.py", line 19, in <module>
soup = BeautifulSoup(html_doc, 'lxml')
File "/Users/chandler.kwok/code/algorithm/.venv/lib/python3.7/site-packages/bs4/__init__.py", line 228, in __init__
% ",".join(features))
bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

简单的按照例子,结果第一步便是报错。原因是 pip3 install beautifulsoup4 还不足以。

Author: Chandler Kwok
Link: http://yoursite.com/2020/05/05/BeautifulSoup/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.