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 ...
随机推荐
- textarea 内容不可编辑 自是适应高度 只读相关属性配置
不可编辑: <textarea disabled="disabled"></textarea> 如果仅仅用于禁止输入(只读,但有用),使用readonly属 ...
- python+django+vue搭建前后端分离项目
以前一直是做基于PHP或JAVA的前后端分离开发,最近跟着python风搭建了一个基于django的前后端分享项目 准备工作:IDE,[JetBrains PyCharm2018][webpack 3 ...
- PAT 1131. Subway Map (30)
最短路. 记录一下到某个点,最后是哪辆车乘到的最短距离.换乘次数以及从哪个位置推过来的,可以开$map$记录一下. #include<map> #include<set> #i ...
- 解决CDH的web界面使用nginx代理一些静态文件无法加载
vim /opt/cm-/share/cmf/webapp/WEB-INF/spring/mvc-config.xml .... 注释此行 <bean class="com.cloud ...
- 打开eclipse 时出现Failed to load the JNIshared libraryd的解决方式
由于电脑重装系统,所以电脑的jdk,与eclipse需要重新配置,今天配置完成jdk之后,打开eclipse出现了Failed to load the JNIshared libraryd的错误,如下 ...
- 【线段树】洛谷 P3372 【模板】线段树 1
动态开结点线段树板子. #include<cstdio> using namespace std; typedef long long ll; ll sumv[400005],delta[ ...
- 【计算几何】【分类讨论】Gym - 101173C - Convex Contour
注意等边三角形的上顶点是卡不到边界上的. 于是整个凸包分成三部分:左边的连续的三角形.中间的.右边的连续的三角形. 套个计算几何板子求个三角形顶点到圆的切线.三角形顶点到正方形左上角距离啥的就行了,分 ...
- 【点分治】【FFT】CDOJ1562 Amaz1ng Prime
统计路径的时候,显然用母函数的思想,可以用FFT来方便统计. 注意!要减去路径两个端点相同的情况!然后再除以二!这样防止重复. 还有就是说啊,点分治的正确姿势还是应该用所有子树的答案减去各个子树分别的 ...
- mysql错误 Access denied for user 'root'@'xxx.xxx.xxx.xxx' (using password: YES)
mysql -u root -p Aaa111222333 grant all privileges on *.* to root@'%' identified by 'aaa111222333; Q ...
- 基于tiny4412的Linux内核移植(支持device tree)(二)
作者信息 作者: 彭东林 邮箱:pengdonglin137@163.com QQ:405728433 平台简介 开发板:tiny4412ADK + S700 + 4GB Flash 要移植的内核版本 ...