python 使用 BeautifulSoup 解析html
下载地址: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(name, attrs, recursive, string, limit, **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的更多相关文章
- Python爬虫 | Beautifulsoup解析html页面
引入 大多数情况下的需求,我们都会指定去使用聚焦爬虫,也就是爬取页面中指定部分的数据值,而不是整个页面的数据.因此,在聚焦爬虫中使用数据解析.所以,我们的数据爬取的流程为: 指定url 基于reque ...
- Python【BeautifulSoup解析和提取网页数据】
[解析数据] 使用浏览器上网,浏览器会把服务器返回来的HTML源代码翻译为我们能看懂的样子 在爬虫中,也要使用能读懂html的工具,才能提取到想要的数据 [提取数据]是指把我们需要的数据从众多数据中挑 ...
- python用BeautifulSoup解析源码时,去除空格及换行符
一.去除空格 strip() " xyz ".strip() # returns "xyz" " xyz ".lstrip() # ...
- python爬虫数据解析之BeautifulSoup
BeautifulSoup是一个可以从HTML或者XML文件中提取数据的python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式. BeautfulSoup是python爬虫三 ...
- 第14.12节 Python中使用BeautifulSoup解析http报文:使用select方法快速定位内容
一. 引言 在<第14.10节 Python中使用BeautifulSoup解析http报文:html标签相关属性的访问>和<第14.11节 Python中使用BeautifulSo ...
- 第14.11节 Python中使用BeautifulSoup解析http报文:使用查找方法快速定位内容
一. 引言 在<第14.10节 Python中使用BeautifulSoup解析http报文:html标签相关属性的访问>介绍了BeautifulSoup对象的主要属性,通过这些属性可以访 ...
- 搭建基于python +opencv+Beautifulsoup+Neurolab机器学习平台
搭建基于python +opencv+Beautifulsoup+Neurolab机器学习平台 By 子敬叔叔 最近在学习麦好的<机器学习实践指南案例应用解析第二版>,在安装学习环境的时候 ...
- Python配合BeautifulSoup读取网络图片并保存在本地
本例为Python配合BeautifulSoup读取网络图片,并保存在本地. BeautifulSoup可代替正则表达式,更好地解析Html文本,获取其中的指定内容,如Tag.Property等 # ...
- python中html解析-Beautiful Soup
1. Beautiful Soup的简介 简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据.官方解释如下: Beautiful Soup提供一些简单的.pyt ...
随机推荐
- vue-music 关于playlist (底部播放列表组件)
建立playlist.vue 组件,在player.vue 组件中引用,点击迷你播放器的播放列表按钮由下至上弹出这个层,所以在player.vue 播放器组件中引用 在playlist.vue 组件中 ...
- HDU 5552 Bus Routes(2015合肥现场赛A,计数,分治NTT)
题意 给定n个点,任意两点之间可以不连边也可以连边.如果连边的话可以染上m种颜色. 求最后形成的图,是一个带环连通图的方案数. 首先答案是n个点的图减去n个点能形成的树. n个点能形成的树的方案数比 ...
- 【剑指offer】顺时针打印数组
顺时针打印数组 题意 例如我们有一个二维数组,如下 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 现在要按照顺时针打印出来,结果应该为: 1 2 3 4 8 12 16 ...
- PMP CMM
CMM和PMP是两个不同的概念域,是用来解决不同问题的.我们所说的CMM,准确的说应该是叫做能力成熟度模型,北京猴子说的软件能力成熟度模型实际上应该称为SW-CMM,是CMM的一个子集.PMP可以看做 ...
- [CF600E]Dsu on tree
题意:树上每个点都有颜色,称一个颜色占领一棵子树,当且仅当没有别的颜色在这棵子树内的数量比它多.求所有子树的占领颜色之和.题解:最显然的是DFS序+主席树或莫队,这里使用Dsu on tree. 每次 ...
- [POJ1980]Unit Fraction Partition(搜索)
Unit Fraction Partition Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 4571 Accepted ...
- python基础之文件操作,函数
文件操作 +模式: r+t w+t a+t r+b w+b a+b 可读可写,其他功能与人,r,w,a相同 f.seek(offset,whence) 文件指针移动 offest的单 ...
- mybatis批量update,返回行数为-1
mybatis批量更新返回结果为-1,是由于mybatis的defaultExExecutorType引起的, 它有三个执行器:SIMPLE 就是普通的执行器:REUSE 执行器会重用预处理语句 ...
- 浅谈js对象及对象属性
对象: ECMA-262把对象定义为 :无序属性的集合,其属性可以包含基本值,对象或者函数. 严格来讲,这就相当于说对象是一组没有特定顺序的值.对象的每一个属性或方法都有一个名字,而每个名字都映射到一 ...
- Codeforces Beta Round #3 A. Shortest path of the king 水题
A. Shortest path of the king 题目连接: http://www.codeforces.com/contest/3/problem/A Description The kin ...