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 ...
随机推荐
- 多线程IO模型
服务端编程,首要问题是选取IO模型.即如何处理大量连接,服务更多的客户端? 我们最早有2种解法,各有不足: 1.阻塞IO,每个连接都需要一个线程. 随着连接数增多,线程数剧增,系统开销太大. 2.非阻 ...
- SQL注入工具实践
程序简介 超级SQL注入工具(SSQLInjection)是一款基于HTTP协议自组包的SQL注入工具,支持出现在HTTP协议任意位置的SQL注入,支持各种类型的SQL注入,支持HTTPS模式注入. ...
- HRBUST 1313 火影忍者之~静音
优先队列. 每次将$n$个人压入优先队列,取出$5$个,最后排序. #include<cstdio> #include<cstring> #include<cmath&g ...
- Bzoj3197/洛谷3296 [SDOI2013]刺客信条assassin(树的重心+树Hash+树形DP+KM)
题面 Bzoj 洛谷 题解 (除了代码均摘自喻队的博客,可是他退役了) 首先固定一棵树,枚举另一棵树,显然另一棵树只有与这棵树同构才有可能产生贡献 如果固定的树以重心为根,那么另一棵树最多就只有重心为 ...
- linux shell date 用当天时间做备份文件名
#!/bin/bash #date 显示时间,我们可以用时间的不同做为备份文件的名字,这样以前的备份就不会被覆盖 datename=$(date +%Y%m%d-%H%M%S) ...
- ASP.NET总结——更改后
这篇重新整理的总结,我做了很久,也在草稿箱中放了很久,一直感觉没有达到和老师谈话后的水平,感觉还是需要增加一些修改,希望读者能提出宝贵意见.既这篇博客之前,我发表了一篇ASP.net的总结,在结构上, ...
- 【转载】R中有关数据挖掘的包
下面列出了可用于数据挖掘的R包和函数的集合.其中一些不是专门为了数据挖掘而开发,但数据挖掘过程中这些包能帮我们不少忙,所以也包含进来. 1.聚类 常用的包: fpc,cluster,pvclust,m ...
- [NOI2015]小园丁与老司机(DP+上下界最小流)
由于每行点的个数不超过1000,所以行内DP可以使用$O(n^2)$算法. 先找到每个点所能直接到达的所有点(x,y,x+y或x-y相同),用排序实现. 第一问:以行为阶段,对于每行,暴力枚举最有路径 ...
- BZOJ 2212 [Poi2011]Tree Rotations(线段树合并)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=2212 [题目大意] 给出一棵二叉树,每个叶节点上有一个权值,现在可以任意交换左右儿子, ...
- Java并发(三):重排序
在执行程序时为了提高性能,提高并行度,编译器和处理器常常会对指令做重排序.重排序分三种类型: 编译器优化的重排序.编译器在不改变单线程程序语义的前提下,可以重新安排语句的执行顺序. 指令级并行的重排序 ...