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 ...
随机推荐
- 转:fortios 5.4后门植入
提示: 1.经过实验,fortios 5.4 beta4也是可以的. 2.在实验时,选择先下载fortios 5.2(做了快照),再升级5.4,则虚拟机挂载需要选择FortiGate-VM-disk1 ...
- Sqli-labs介绍、下载、安装
SQLI和sqli-labs介绍 SQLI,sql injection,我们称之为sql注入.何为sql,英文:Structured Query Language,叫做结构化查询语言.常见的结构化数据 ...
- 【UOJ #34】多项式乘法
http://uoj.ac/problem/34 看了好长时间的FFT和NTT啊qwq在原根那块磨蹭了好久_(:з」∠)_ 首先设答案多项式的长度拓展到2的幂次后为n,我们只要求出一个g(不是原根)满 ...
- 【转载】随机生成k个范围为1-n的随机数,其中有多少个不同的随机数?
来源:http://www.cnblogs.com/haolujun/archive/2012/11/11/2765102.html 假如现在让你随机生成k个范围在1-n内的随机数,那么你能得到多少个 ...
- 【状压DP】BZOJ2734-[HNOI2012]集合选数
已经八月份了药丸,开始肝作业并且准备高考啦!! [题目大意] <集合论与图论>这门课程有一道作业题,要求同学们求出{1, 2, 3, 4, 5}的所有满足以 下条件的子集:若 x 在该子集 ...
- Uncaught SyntaxError: Invalid shorthand property initializer
$.ajax({ url : '../../collateralQuery/getCollateralQueryDetail', type : 'POST', data : {}, dataType ...
- (转) Unity3D常用代码收集总结
//创建一个名为"Player"的游戏物体 //并给他添加刚体和立方体碰撞器. player=new GameObject("Player"); player. ...
- Web安全开发指南--异常错误处理与日志审计
1.异常错误处理与日志审计 5.1.日志审计系统安全规则 1 日志系统能够记录特定事件的执行结果(比如 成功或失败). 确保日志系统包含如下重要日志信息: 1. 日志发生的时间: 2. 事件的严重 ...
- node.js中express-session配置项详解
官方地址:https://www.npmjs.com/package/express-session 作用:用指定的参数创建一个session中间件,sesison数据不是保存在cookie中,仅仅s ...
- 【转】Python IDE for Eclipse
原文地址 PyDev is a plugin that enables Eclipse to be used as a Python IDE (supporting also Jython and I ...