下载地址:http://www.crummy.com/software/BeautifulSoup/bs4/download/4.3/beautifulsoup4-4.3.2.tar.gz

说明:这个版本使用python 2.7比较好。

install: 解压缩,然后运行python setup.py install

linux系统还可以:sudo apt-get install Python-bs4

还可以:pip install beautifulsoup4

官方文档:

http://www.crummy.com/software/BeautifulSoup/bs4/doc/

(也可以使用 pyQuery)

使用

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_str, 'html.parser')

输出文档

with open('test.html', 'w') as f:
f.write(soup.prettify().encode('utf-8'))

当你调用__str__,prettify或者renderContents时, 你可以指定输出的编码。默认的编码(str使用的)是UTF-8。 下面是处理ISO-8851-1的串并以不同的编码输出同样的串的例子。 soup.__str__("ISO-8859-1")

四大对象种类

Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:

  • Tag: 对于 Tag,它有两个重要的属性,是 name 和 attrs
  • NavigableString: 获取标签内部的文字
  • BeautifulSoup:you can treat it as a Tag object
  • Comment:获取注释 <!-- comment -->

Tag:

  • print type(soup.a)
    #<class 'bs4.element.Tag'>
    print soup.p.attrs
    #{'class': ['title'], 'name': 'dromouse'}
  • css_soup = BeautifulSoup('<p class="body strikeout"></p>')
    css_soup.p['class']
    # ["body", "strikeout"]

NavigableString:

  • print soup.p.string
    #The Dormouse's story

足够有用:

soup.title
# <title>The Dormouse's story</title> soup.title.name
# u'title' soup.title.string
# u'The Dormouse's story' soup.title.parent.name
# u'head' soup.p
# <p class="title"><b>The Dormouse's story</b></p> soup.p['class']
# u'title' soup.a
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a> soup.find_all('a')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
print soup.find("a", attrs={"class": "sister"}) #只找第一个
print soup.find_all("a", attrs={"class": "sister"}, limit=2)
import re
soup.find(string=re.compile("sisters"))
soup.find(id="link3")
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
head_tag.contents
[<title>The Dormouse's story</title>] head_tag.children
[<title>The Dormouse's story</title>] title_tag.parent
# <head><title>The Dormouse's story</title></head> sibling_soup.b.next_sibling
# <c>text2</c> sibling_soup.c.previous_sibling
# <b>text1</b>

find_all == findAll

find_all(nameattrsrecursivestringlimit**kwargs)

我的程序:

from bs4 import BeautifulSoup

def parse_html(text):
soup = BeautifulSoup(text, from_encoding="UTF-8")
# 找出id="historyTable"的table, 找到它内部的第一个table,获取所有的 tr
target = soup.find(id="historyTable").find('table').findAll('tr')
results = []
rec = []
for tr in target[1:]: # ignore th
tds = tr.findAll('td') # 获取所有的 td
build_no = str(tds[1].span.string.strip()) # 找出第二个td的span节点,取出它的text内容
patch = str(tds[0].a.string) # 第一个td 的 a 节点的text
status_node = tds[2].find('a')
status = str(status_node.find('span').string)
status_link = '%s/%s'%(TEAMCITY_HOME, status_node.attrs['href']) # 属性
started = str(tds[5].string.replace(u'\xa0', ' ')) # 去掉无法解析的字符 print '-'*10
print '%s\t'%patch,
print '%s\t'%build_no,
print '%s\t'%status,
print '%s\t'%started

python 使用 BeautifulSoup 解析html的更多相关文章

  1. Python爬虫 | Beautifulsoup解析html页面

    引入 大多数情况下的需求,我们都会指定去使用聚焦爬虫,也就是爬取页面中指定部分的数据值,而不是整个页面的数据.因此,在聚焦爬虫中使用数据解析.所以,我们的数据爬取的流程为: 指定url 基于reque ...

  2. Python【BeautifulSoup解析和提取网页数据】

    [解析数据] 使用浏览器上网,浏览器会把服务器返回来的HTML源代码翻译为我们能看懂的样子 在爬虫中,也要使用能读懂html的工具,才能提取到想要的数据 [提取数据]是指把我们需要的数据从众多数据中挑 ...

  3. python用BeautifulSoup解析源码时,去除空格及换行符

    一.去除空格 strip()   " xyz ".strip() # returns "xyz"   " xyz ".lstrip() # ...

  4. python爬虫数据解析之BeautifulSoup

    BeautifulSoup是一个可以从HTML或者XML文件中提取数据的python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式. BeautfulSoup是python爬虫三 ...

  5. 第14.12节 Python中使用BeautifulSoup解析http报文:使用select方法快速定位内容

    一. 引言 在<第14.10节 Python中使用BeautifulSoup解析http报文:html标签相关属性的访问>和<第14.11节 Python中使用BeautifulSo ...

  6. 第14.11节 Python中使用BeautifulSoup解析http报文:使用查找方法快速定位内容

    一. 引言 在<第14.10节 Python中使用BeautifulSoup解析http报文:html标签相关属性的访问>介绍了BeautifulSoup对象的主要属性,通过这些属性可以访 ...

  7. 搭建基于python +opencv+Beautifulsoup+Neurolab机器学习平台

    搭建基于python +opencv+Beautifulsoup+Neurolab机器学习平台 By 子敬叔叔 最近在学习麦好的<机器学习实践指南案例应用解析第二版>,在安装学习环境的时候 ...

  8. Python配合BeautifulSoup读取网络图片并保存在本地

    本例为Python配合BeautifulSoup读取网络图片,并保存在本地. BeautifulSoup可代替正则表达式,更好地解析Html文本,获取其中的指定内容,如Tag.Property等 # ...

  9. python中html解析-Beautiful Soup

    1. Beautiful Soup的简介 简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据.官方解释如下: Beautiful Soup提供一些简单的.pyt ...

随机推荐

  1. 《深入理解Android2》读书笔记(一)

    2017-5-12 从今天开始估计有一段空闲时间,开始阅读<深入理解Android2>,并写读书笔记. 第一章搭建环境直接略过. 第二章是Binder,暂时略过 7大类服务包括:1.And ...

  2. scrapy抓取拉勾网职位信息(二)——拉勾网页面分析

    网站结构分析: 四个大标签:首页.公司.校园.言职 我们最终是要得到详情页的信息,但是从首页的很多链接都能进入到一个详情页,我们需要对这些标签一个个分析,分析出哪些链接我们需要跟进. 首先是四个大标签 ...

  3. Did Pong Lie? (差分系统 判负环)

    Did Pong Lie? 时间限制: 5 Sec  内存限制: 128 MB提交: 68  解决: 15[提交][状态][讨论版] 题目描述 Doctor Pong has two arrays o ...

  4. CSS中包含块原理解析

    CSS包含块原理解析 确定CSS中的包含块也确定就是元素的父元素.关键是:看元素是如何定位的.确定包含块很重要,比如设置百分比.另外也可以进行样式的继承等等. 分两个情况: 相对定位和静态定位 静态定 ...

  5. oracle 查看16进制

    DUMP function is useful for this purpose. SQL> select dump(C1) from test; DUMP(C1)--------------- ...

  6. ES5 的 Array

    1: Array.isArray判断是否为数组 Array.isArray([1, 2, 3]); // true Array.isArray({foo: 123}); // false // Pol ...

  7. luogu P1137 旅行计划

    题目描述 小明要去一个国家旅游.这个国家有N个城市,编号为1-N,并且有M条道路连接着,小明准备从其中一个城市出发,并只往东走到城市i停止. 所以他就需要选择最先到达的城市,并制定一条路线以城市i为终 ...

  8. 全网第二好懂的FFT(快速傅里叶变换)

    声明:本FFT是针对OI的.专业人员请出门左拐. Ⅰ前言 很久以前,我打算学习FFT. 然而,算法导论讲的很详细,却看不懂.网上博客更别说了,什么频率之类的都来了.我暗自下了决心:写一篇人看得懂的FF ...

  9. 【线性筛】【质因数分解】【约数个数定理】hdu6069 Counting Divisors

    d(x)表示x的约数个数,让你求(l,r<=10^12,r-l<=10^6,k<=10^7) #include<cstdio> using namespace std; ...

  10. [CF340D]Bubble Sort Graph/[JZOJ3485]独立集

    题目大意: 给你一个序列,对序列中所有逆序对之间连一条边,问图中最大独立集为多大,有哪些点一定在最大独立集中. 思路: 在纸上画一下发现最大独立集一定是元序列的一个LIS,最大独立集必经点就是所有LI ...