【6】网络与网页-3-解析html--beautifulsoup

BeautifulSoup库是解析、遍历、维护“标签树”的功能库

一、简介

官方文档:http://beautifulsoup.readthedocs.io/zh_CN/latest/

安装

sudo pip install beautifulsoup4

二、Beautiful Soup库的基本元素

<p class=“title”> ... </p>
p==>名称 Name 成对出现
class ==>属性 Attributes 0个或多个

from bs4 import BeautifulSoup
soup = BeautifulSoup(demo, 'html.parser')
soup2 = BeautifulSoup('/qqin/demo.html', 'html.parser')

获得标签内的内容

snps_names = soup2.find_all('div','gene-position pull-left')
gene_names = soup2.find_all('div','gene-name pull-left')
for jjj in range(len(snps_names)):
	one_snp_name = snps_names[jjj].get_text().strip()
	
.get_text("\t") 可以指定分隔符

提取标签的内容:

soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
tag = soup.b

tag.name = "blockquote"
tag['class'] = 'verybold'
tag['id'] = 1
tag
# <blockquote class="verybold" id="1">Extremely bold</blockquote>

del tag['class']
del tag['id']
tag
# <blockquote>Extremely bold</blockquote>

如果是已经通过find_all获得<a>的内容,直接通过b['href']既可以获得href对应内容

查找包含某个内容的class

pheno_class = soup.find_all('div',re.compile('h2 y1 ff1 fs0 fc0 sc0 ls0 ws0'))

三、Beautiful Soup库解析器

解析器 使用方法 条件
bs4的HTML解析器 BeautifulSoup(mk,'html.parser') 安装bs4库
lxml的HTML解析器 BeautifulSoup(mk,'lxml') pip install lxml
lxml的XML解析器 BeautifulSoup(mk,'xml') pip install lxml
html5lib的解析器 BeautifulSoup(mk,'html5lib') pip install html5lib

四、BeautifulSoup类的基本元素

	<p class=“title”> ... </p>

基本元素 说明

Tag 标签,最基本的信息组织单元,分别用<>和</>标明开头和结尾
Name 标签的名字,<p>...</p>的名字是'p',格式:<tag>.name
Attributes 标签的属性,字典形式组织,格式:<tag>.attrs
NavigableString 标签内非属性字符串,<>...</>中字符串,格式:<tag>.string
Comment 标签内字符串的注释部分,一种特殊的Comment类型

案例:

from bs4 import BeautifulSoup
soup = BeautifulSoup(demo, 'html.parser')
print soup.prettify()
   This is a python demo page
<b> 
</b><html>
 <head>
  <title>
   This is a python demo page
  </title>
 </head>
 <body>
  <p class="title">
   <b>
	The demo python introduces several python courses.
   </b>
  </p>
  <p class="course">
   Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
   <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
	Basic Python
   </a>
   and
   <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
	Advanced Python
   </a>
   .
  </p>
 </body>
</html>

print soup.title
<title>This is a python demo page</title>

print soup.a
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
print soup.a.name
a

print soup.a.parent.name
p

print soup.a.parent.parent.name
body


print soup.a.attrs
{u'href': u'http://www.icourse163.org/course/BIT-268001', u'class': [u'py1'], u'id': u'link1'}

print soup.a.attrs['class']
[u'py1']

print type(soup.a.attrs)
<type 'dict'>
<type 'dict'>

一个可以有0或多个属性,字典类型

print soup.a.string
Basic Python
NavigableString可以跨越多个层次


new_soup = BeautifulSoup('<b><!--hahahah--></b><p>cccccccc</p>','html.parser')
print new_soup.b.string
hahahah

print type(new_soup.b.string)
<class 'bs4.element.Comment'>

print new_soup.p.string
cccccccc

print type(new_soup.p.string)
<class 'bs4.element.NavigableString'>

Comment是一种特殊类型

五、 基于bs4库的HTML内容遍历方法

HTML基本格式

标签树的下行遍历

属性 说明

.contents 子节点的列表,将所有儿子节点存入列表
.children 子节点的迭代类型,与.contents类似,用于循环遍历儿子节点
.descendants 子孙节点的迭代类型,包含所有子孙节点,用于循环遍历

案例:

soup = BeautifulSoup(demo, 'html.parser')
print soup.head
<head><title>This is a python demo page</title></head>

print soup.head.contents
[<title>This is a python demo page</title>]

print soup.body.contents
[u'\n', <p class="title"><b>The demo python introduces several python courses.</b></p>, u'\n', <p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>, u'\n'] 

print len(soup.body.contents)
 5

<p class="title"><b>The demo python introduces several python courses.</b></p>

for child in soup.body.children:
<span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 1.5;">      print child #遍历儿子节点
</span>for child in soup.body.descendants:
  print(child) #遍历子孙节点

标签树的上行遍历

.parent 节点的父亲标签
.parents 节点先辈标签的迭代类型,用于循环遍历先辈节点

案例:

from bs4 import BeautifulSoup
soup = BeautifulSoup(demo, 'html.parser')

print soup.title.parent
<span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 1.5;">#<head><title>This is a python demo page</title></head>

print soup.html.parent

print soup.parent
# None

for parent in soup.a.parents:
 if parent is not None:
 print parent.name
 else:
 print parent.name

# p
# body
# html
# [document]</span>

标签树的平行遍历

.next_sibling 返回按照HTML文本顺序的下一个平行节点标签
.previous_sibling 返回按照HTML文本顺序的上一个平行节点标签
.next_siblings 迭代类型,返回按照HTML文本顺序的后续所有平行节点标签
.previous_siblings 迭代类型,返回按照HTML文本顺序的前续所有平行节点标签

案例:

#coding:UTF-8
import requests
from bs4 import BeautifulSoup


r = requests.get('http://python123.io/ws/demo.html')

demo =r.text
soup = BeautifulSoup(demo, 'html.parser')

print soup.a.next_sibling
 # and

print soup.a.next_sibling.next_sibling
# <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>


print soup.a.previous_sibling
# Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:

PPT(图)


for sibling in soup.a.next_sibling:
	print(sibling) 遍历后续节点
for sibling in soup.a.previous_sibling:
	print(sibling)  遍历前续节点

六、 基于bs4库的HTML格式输出

能否让HTML内容更加“友好”的显示?

bs4库的prettify()方法

#coding:UTF-8
import requests
from bs4 import BeautifulSoup
r = requests.get('http://python123.io/ws/demo.html')
demo =r.text
soup = BeautifulSoup(demo, 'html.parser')

print soup.prettify()
.prettify()为HTML文本<>及其内容增加更加'\n' .prettify()可用于标签,方法:<tag>.prettify()

print soup.a.prettify()

bs4库将任何HTML输入都变成utf‐8编码

Python 3.x默认支持编码是utf‐8,解析无障碍

七、 信息的抓取

信息标记的三种形式

XML
Tag: <img src=“china.jpg” size=“10”> ... </img>
img: 名称 Name
src,size: 属性 Attribute

JSON (JavsScript Object Notation)

有类型的键值对 key:value

多值用[,]组织

键值对嵌套用{,}

YAML

无类型键值对 key:value
缩进表达所属关系
‐ 表达并列关系
| 表达整块数据 # 表示注释

三种信息标记的比较

  • XML 最早的通用信息标记语言,可扩展性好,但繁琐 (Internet上的信息交互与传递)
  • JSON 信息有类型,适合程序处理(js),较XML简洁 (移动应用云端和节点的信息通信,无注释)
  • YAML 信息无类型,文本信息比例最高,可读性好 (各类系统的配置文件,有注释易读)

信息提取的一般方法

方法一:完整解析信息的标记形式,再提取关键信息(XML JSON YAML)

需要标记解析器,例如:bs4库的标签树遍历

优点:信息解析准确 缺点:提取过程繁琐,速度慢

方法二:无视标记形式,直接搜索关键信息 (搜索)

对信息的文本查找函数即可

优点:提取过程简洁,速度较快 缺点:提取结果准确性与信息内容相关

融合方法:结合形式解析与搜索方法,提取关键信息(XML JSON YAML 搜索)

需要标记解析器及文本查找函数

<>.find_all(name, attrs, recursive, string, **kwargs)
name : 对标签名称的检索字符串
 attrs: 对标签属性值的检索字符串,可标注属性检索
 ∙ recursive: 是否对子孙全部检索,默认True
 string: <>...</>中字符串区域的检索字符串
 
 print soup.find_all('a')
 print soup.find_all(['a','b'])
 
 print soup.find_all('p','course')
 print soup.find_all(id='link1')
 print soup.find_all(id=re.compile('link'))  #包含link开头的所有属性
  print soup.find_all('a')
 print soup.find_all(['a','b'])
 
 print soup.find_all('p','course')
 print soup.find_all(id='link1')
 print soup.find_all(id=re.compile('link')) #包含link开头的所有属性
 
 print soup.find_all('a')
 [<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]

 print soup.find_all('a',recursive=False) #下一级不列出来
 []
 
 简写
 <tag>(..) 等价于 <tag>.find_all(..)
 soup(..) 等价于 soup.find_all(..)<span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 1.5;">扩展方法:</span>


<>.find() 搜索且只返回一个结果,同.find_all()参数
<>.find_parents() 在先辈节点中搜索,返回列表类型,同.find_all()参数
<>.find_parent() 在先辈节点中返回一个结果,同.find()参数
<>.find_next_siblings() 在后续平行节点中搜索,返回列表类型,同.find_all()参数
<>.find_next_sibling() 在后续平行节点中返回一个结果,同.find()参数
<>.find_previous_siblings() 在前序平行节点中搜索,返回列表类型,同.find_all()参数
<>.find_previous_sibling() 在前序平行节点中返回一个结果,同.find()参数

八、报错:

1.Invalid conversion specification

tmplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
	print tmplt.format('排名',"学校名称","总分",unichr(12288).encode('utf-8'))
	
ValueError: Invalid conversion specification
print tmplt.format('排名',"学校名称","总分",unichr(12288))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u3000' in position 0: ordinal not in range(128)

当中文字符宽度不够时,采用西文字符填充;中西文字符占用宽度不同 采用中文字符的空格填充 chr(12288)

python 2
chr( K ) 将编码K 转为字符,K的范围是 0 ~ 255
python 3
chr( K ) 将编码K 转为字符,K的范围是 0 ~ 65535
  1. BeautifulSoup会有警告如果我们创建对象时传递的是文件名而不是文件对象时,比如:

    soup_foo = BeautifulSoup(“foo.html”) 警告如下: UserWarning: “foo.html” looks like a filename, not markup. You should probably open this file and pass the filehandle into Beautiful Soup.

但是Beautiful仍然会将"foo.html"当做字符串处理。 同样的如果我们传递一个URL代替URL文件对象的话,也会被当做字符串处理。

解决办法:

with open("foo.html","r") as foo_file:  
soup_foo = BeautifulSoup(foo_file)  

3.编码问题

在解析一个网页的时候,不停出现乱码的问题,其实最关键的就是需要知道编码的方式,可以通过python的 chardet知道编码方式,然后对整个读取的文本decode一下,例如下面的例子,input_html文件采用的是GBK的编码方式

#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
with open(input_html, "r") as foo_file:
    soup = BeautifulSoup(foo_file.read().decode("GBK"),"html.parser")

这里不是太明白,为什么,我对某些行做decode(“GBK”)就会出现乱码,对整个decode,最后的结果就没事哒

xml文件的解析:

<?xml version="1.0" encoding="utf-8" ?>
<PredictionResults>
    <Sequence>
        <Name>HLA-DRB5*0101_1_325.356891</Name>
        <AASequence>ISIVQMAPVSAMVRM</AASequence>
        <PFrequency>..CAAAAAHDGBA..</PFrequency>
        <Results>
    <Result id="01">..AAAACSRWAAA..</Result>
    <Result id="02">..D     AEYD ..</Result>
    <Result id="03">..S     SDZ  ..</Result>
    <Result id="04">..      WAE  ..</Result>
    <Result id="05">..      E W  ..</Result>
    <Result id="06">..      V B  ..</Result>
    <Result id="07">..      Y C  ..</Result>
    <Result id="08">..      C    ..</Result>
        </Results>
    </Sequence>

解析代码:

soup = BeautifulSoup(open(input_file),'xml')

for one_seq in soup.findChildren('Sequence'):
    seq_name = one_seq.findChildren('Name')[0].get_text()
    seq_score = seq_name.split("_")[-1]
    aa_seq = one_seq.findChildren('AASequence')[0].get_text()
    pfsc_seq = one_seq.findChildren('PFrequency')[0].get_text()

参考资料:

北京理工大学嵩天老师的课件

http://blog.csdn.net/abclixu123/article/details/25841227

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn