模块的引入

对于HTML和XML

 

  1. from BeautifulSoup import BeautifulSoup # For HTML 
  2. from BeautifulSoup import BeautifulSoup # For XML 

创建BeautifulSoup对象(以打开百度首页为例)

 

  1. # 只保留关键代码 
  2. import urllib.request 
  3. page = urllib.request.urlopen('http://www.baidu.com/'
  4. soup = BeautifulSoup(page) 

查找HTML中指定的元素

(1)根据tag查找

 

  1. # 例如 
  2. soup.html.head.title # title tag 
  3. soup.html.head.title.name # title tag's name 
  4. soup.html;head.title.string # title tag's content text 
  5. # 当然也可以 
  6. soup.title 

(2)根据HTML内容查找

 

  1. import re 
  2. soup.findAll(text = re.compile('para')) 
  3. soup.findAll(text = re.compile('para'))[0].parent 
  4. soup.findAll(text = re.compile('para'))[0].parent.contents 

(3)根据css属性查找

 

  1. soup.findAll(id = re.compile('para$')) 
  2. soup.findAll(attrs = (id: re.compile('para$'))) 

 

编码处理

【1】内部使用Unicode编码,自动检测并转换为Unicode编码。

【2】编码检测的顺序为

 

  1. 1、创建soup时候传递的fromEncoding参数 
  2. 2、XML/HTML文件自己定义的编码 
  3. 3、文件开始的几个字节的编码特性 
  4. 4、若安装了chardet,用chardet检测文件编码 
  5. 5、UTF-8 
  6. 6、Windows-1252 
  7. …… 

【3】默认输出的是UTF-8

【4】使用soup.original_encoding给出Beautiful Soup检测出的编码。

 

  1. soup.original_encoding # bs4 syntax 
  2. soup.originalEncoding # bs3 syntax 

 

One More Thing - Tips

检测a标签的href属性

 

  1. for link in soup.findAll('a', href = True): 
  2.     print(link['href'])  # Py3K syntax