下载地址: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. PowerShell 获取系统的硬件信息

    1.获取系统的BIOS的信息: Get-WMIObject -Class Win32_BIOS 2.获取内存信息: Get-WMIObject -Class Win32_PhysicalMemory ...

  2. SpringMVC中为什么要配置Listener和Servlet

    一直以来,我们使用SpringMVC的时候习惯性都配置一个ContextLoaderListener,虽然曾经有过疑问,配置的这个监听器和Servlet究竟做了什么,但也没深究. 要说任何Web框架都 ...

  3. 洛谷——P1292 倒酒

    P1292 倒酒 题目描述 Winy是一家酒吧的老板,他的酒吧提供两种体积的啤酒,a ml和b ml,分别使用容积为a ml和b ml的酒杯来装载. 酒吧的生意并不好.Winy发现酒鬼们都非常穷.有时 ...

  4. Codeforces Round #433 (Div. 2, based on Olympiad of Metropolises) D. Jury Meeting(双指针模拟)

    D. Jury Meeting time limit per test 1 second memory limit per test 512 megabytes input standard inpu ...

  5. 多进程失败拉起的demo

    #include <iostream> #include <vector> #include <unistd.h> #include <stdlib.h> ...

  6. Flask实战第58天:发布帖子功能完成

    发布帖子后台逻辑完成 首先给帖子设计个模型,编辑apps.models.py class PostModel(db.Model): __tablename__ = 'post' id = db.Col ...

  7. 【uva 10294】 Arif in Dhaka (First Love Part 2) (置换,burnside引理|polya定理)

    题目来源:UVa 10294 Arif in Dhaka (First Love Part 2) 题意:n颗珠子t种颜色 求有多少种项链和手镯 项链不可以翻转 手镯可以翻转 [分析] 要开始学置换了. ...

  8. SQLSEVER 中的那些键和约束

    SQL Server中有五种约束类型,分别是 PRIMARY KEY约束.FOREIGN KEY约束.UNIQUE约束.DEFAULT约束.和CHECK约束.查看或者创建约束都要使用到 Microso ...

  9. 【20181019T1】加密【逆元+位运算】

    题面 [错解] 可能要逆推 <<就是乘法,好做 但^是什么东西? 欸暴力map70分,索性妥协 [正解] 注意^是自己异或上自己右移,前i位就是t的前i位 往后推就好 代码

  10. [NOIP 2004] T3 合并果子

    居然和BZOJ 1724完全一样o(╯□╰)o #include <bits/stdc++.h> using namespace std; typedef long long ll; in ...