前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >爬虫入门(三):BeautifulSoup

爬虫入门(三):BeautifulSoup

作者头像
一点儿也不潇洒
发布2018-08-07 10:12:10
4450
发布2018-08-07 10:12:10
举报

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

import BeautifulSoup 

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

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

5 搜索节点(find_all,find)

#方法: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')

6 访问节点信息

#得到节点:Python  
#获得查找到的节点的标签名称  
node.name
#获得查找到的a节点的href属性   
node['herf']   
#获取查找到的a节点的链接文字  
node.get_text()  

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()  #名称,属性,文字
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-10-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档