爬虫入门(三):BeautifulSoup

date: 2016-10-10 08:49:53

BeautifulSoup,网页解析器,DOM树,结构化解析。

1 安装

BeautifulSoup4.x 兼容性不好,选用BeautifulSoup3.x + Python 2.x.
下载安装包放在/lib文件下,DOS下输入:
1 python setup.py build
2 python setup.py install

2 测试

IDLE里输入:

import BeautifulSoup

print BeautifulSoup
运行显示:
<module 'BeautifulSoup' from 'C:\Python27\lib\site-packages\BeautifulSoup.pyc'>

3 网页解析器-BeautifulSoup-语法

由HTLM网页可进行以下活动:

  1. 创建BeautifulSoup对象
  2. 搜索节点find_all/find
  3. 访问节点名称、属性、文字

例如:
<a herf='123.html' class='article_link'> Python</a>

节点名称:a

节点属性:herf='123.html'
节点属性:class='article_link'

节点内容:Python

4 创建BeautifulSoup对象

<pre>
import BeautifulSoup

根据HTML网页字符串创建BeautifulSoup对象

soup = BeautifulSoup(
html_doc, #HTLM文档字符串
'htlm.parser' #HTLM解析器
from_encoding='utf8' #HTLM文档的编码
)
</pre>

5 搜索节点(find_all,find)
<pre>

方法:find_all(name,attrs,string)

查找所有标签为a的节点

soup.find_all('a')

查找所有标签为a,链接符合/view/123.htlm形式的节点

soup.find_all('a',href='/view/123.htlm')
soup.find_all('a',href=re.compile(r'/view/d+.htm'))

查找所有标签为div,class为abc,文字为Python的节点

soup.find_all('div',class_='abc',sting='Python')
</pre>

6 访问节点信息
<pre>

得到节点:<a href='1.html'>Python</a>

获得查找到的节点的标签名称

node.name

获得查找到的a节点的href属性

node['herf']

获取查找到的a节点的链接文字

node.get_text()
</pre>

7 实例测试

#coding:utf-8
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, 'htlm.parser', from_encoding='utf-8') #参数:文档字符串,解析器,指定编码

print '获取所有的链接'
links = soup.find_all('a')  #获取所有的链接
for link in links:
    print link.name, link['href'],link.get_text()  #名称,属性,文字
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Python爬虫入门(urllib+Beautifulsoup) 本文包括:1、爬虫简单介绍2、爬虫架构三大模块3...
    廖少少阅读 9,980评论 0 6
  • 一、前言 上一篇演示了如何使用requests模块向网站发送http请求,获取到网页的HTML数据。这篇来演示如何...
    阿里波特阅读 3,042评论 8 23
  • 声明:本文讲解的实战内容,均仅用于学习交流,请勿用于任何商业用途! 一、前言 强烈建议:请在电脑的陪同下,阅读本文...
    Bruce_Szh阅读 12,852评论 6 28
  • 雅丹只是我的食客而已。 我坐在一旁,看着她把那些红的白的肉一勺一勺的抹进嘴里,我的手上还沾着刚才炒菜时没撒干净的盐...
    左左左FiveNo阅读 258评论 0 0
  • 接着上一次的说,我的辞职信送到人事部经理办公室,还没递给他,他就直接对我说:“白琳,董事长那里需要一个小助...
    简书迷妹阅读 154评论 0 0