发表于: 2018-01-09 22:38:20

2 893


今天完成的事情:学习BeautifulSoup


1、BeautifulSoup介绍

BeautifulSoup是一个可以从HTML或XML文件中提取数据的Python库,利用它能方便的实现网页信息的抓取,是个爬虫利器。

中文文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/


2、安装

Windows下安装:命令行下运行 pip install beautifulsoup4

PyCharm开发环境下安装:File->Settings->Project Interpreter,点击“+”号搜索到“beautifulsoup4“,安装即可。


3、学习代码示例

from bs4 import BeautifulSoup
import re
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 litter" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

soup = BeautifulSoup(html_doc,"html.parser")
print('===================')
print('1---  ', soup.title)
print('2---  ', soup.title.string)
print('3---  ', soup.title.name)
print('4---  ', soup.title.parent.name)
print('5---  ', soup.p)
print('6---  ', soup.p['class'])
print('7---  ', soup.p.attrs['class'])
print('8---  ', soup.a)
print('9---  ', soup.find(id='link3'))
print('10--  ', soup.find('p', {'class': 'story'}).get_text())
for link in soup.findAll('a'):
    print('11--  ', link.get_text())
for link2 in soup.select('.sister'):
    print('12--  ', link2.get('href'))
for tag in soup.find_all(re.compile("^b")):
    print('13--  ', tag.name)


运行结果如下:

D:\PycharmProjects\untitled\venv\Scripts\python.exe D:/PycharmProjects/PyCode/beautifulsoup.py

===================

1---   <title>The Dormouse's story</title>

2---   The Dormouse's story

3---   title

4---   head

5---   <p class="title"><b>The Dormouse's story</b></p>

6---   ['title']

7---   ['title']

8---   <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

9---   <a class="sister litter" href="http://example.com/tillie" id="link3">Tillie</a>

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

11--   Elsie

11--   Lacie

11--   Tillie

12--   http://example.com/elsie

12--   http://example.com/lacie

12--   http://example.com/tillie

13--   body

13--   b

Process finished with exit code 0


收获:在学习 BeautifulSoup的过程中,同时也初步学习了正则表达式的使用。我感觉这两者配合使用,在爬虫领域内,应该大有作为吧。





返回列表 返回列表
评论

    分享到