亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python使用BeautifulSoup庫(kù)解析HTML基本使用教程

 更新時(shí)間:2016年03月31日 16:07:00   作者:kuring  
這篇文章主要介紹了Python使用BeautifulSoup庫(kù)解析HTML基本使用教程,文中主要對(duì)其適合于制作爬蟲方面的特性進(jìn)行了解析,需要的朋友可以參考下

 BeautifulSoup是Python的一個(gè)第三方庫(kù),可用于幫助解析html/XML等內(nèi)容,以抓取特定的網(wǎng)頁(yè)信息。目前最新的是v4版本,這里主要總結(jié)一下我使用的v3版本解析html的一些常用方法。

準(zhǔn)備

1.Beautiful Soup安裝

為了能夠?qū)?yè)面中的內(nèi)容進(jìn)行解析,本文使用Beautiful Soup。當(dāng)然,本文的例子需求較簡(jiǎn)單,完全可以使用分析字符串的方式。

執(zhí)行

sudo easy_install beautifulsoup4

即可安裝。

2.requests模塊的安裝

requests模塊用于加載要請(qǐng)求的web頁(yè)面。

在python的命令行中輸入import requests,報(bào)錯(cuò)說(shuō)明requests模塊沒有安裝。

我這里打算采用easy_install的在線安裝方式安裝,發(fā)現(xiàn)系統(tǒng)中并不存在easy_install命令,輸入sudo apt-get install python-setuptools來(lái)安裝easy_install工具。

執(zhí)行sudo easy_install requests安裝requests模塊。

基礎(chǔ)

1.初始化
   導(dǎo)入模塊

#!/usr/bin/env python
from BeautifulSoup import BeautifulSoup    #process html
#from BeautifulSoup import BeautifulStoneSoup #process xml
#import BeautifulSoup             #all

    創(chuàng)建對(duì)象:str初始化,常用urllib2或browser返回的html初始化BeautifulSoup對(duì)象。

doc = ['hello',
    '
This is paragraph one of ptyhonclub.org.',
    '
This is paragraph two of pythonclub.org.',
    '']
soup = BeautifulSoup(''.join(doc))

    指定編碼:當(dāng)html為其他類型編碼(非utf-8和asc ii),比如GB2312的話,則需要指定相應(yīng)的字符編碼,BeautifulSoup才能正確解析。

htmlCharset = "GB2312"
soup = BeautifulSoup(respHtml, fromEncoding=htmlCharset)

2.獲取tag內(nèi)容
   尋找感興趣的tag塊內(nèi)容,返回對(duì)應(yīng)tag塊的剖析樹

head = soup.find('head')
#head = soup.head
#head = soup.contents[0].contents[0]
print head

    返回內(nèi)容:hello
   說(shuō)明一下,contents屬性是一個(gè)列表,里面保存了該剖析樹的直接兒子。

html = soup.contents[0]    # <html> ... </html>
head = html.contents[0]    # <head> ... </head>
body = html.contents[1]    # <body> ... </body>

3.獲取關(guān)系節(jié)點(diǎn)
   使用parent獲取父節(jié)點(diǎn)

body = soup.body
html = body.parent       # html是body的父親

    使用nextSibling, previousSibling獲取前后兄弟

head = body.previousSibling  # head和body在同一層,是body的前一個(gè)兄弟
p1 = body.contents[0]     # p1, p2都是body的兒子,我們用contents[0]取得p1
p2 = p1.nextSibling      # p2與p1在同一層,是p1的后一個(gè)兄弟, 當(dāng)然body.content[1]也可得到

    contents[]的靈活運(yùn)用也可以尋找關(guān)系節(jié)點(diǎn),尋找祖先或者子孫可以采用findParent(s), findNextSibling(s), findPreviousSibling(s)

4.find/findAll用法詳解
   函數(shù)原型:find(name=None, attrs={}, recursive=True, text=None, **kwargs),findAll會(huì)返回所有符合要求的結(jié)果,并以list返回。
   tag搜索

find(tagname)                 # 直接搜索名為tagname的tag 如:find('head')
find(list)                   # 搜索在list中的tag,如: find(['head', 'body'])
find(dict)                   # 搜索在dict中的tag,如:find({'head':True, 'body':True})
find(re.compile(''))              # 搜索符合正則的tag, 如:find(re.compile('^p')) 搜索以p開頭的tag
find(lambda)            # 搜索函數(shù)返回結(jié)果為true的tag, 如:find(lambda name: if len(name) == 1) 搜索長(zhǎng)度為1的tag
find(True)                   # 搜索所有tag

   attrs搜索

find(id='xxx')                 # 尋找id屬性為xxx的
find(attrs={id=re.compile('xxx'), algin='xxx'}) # 尋找id屬性符合正則且algin屬性為xxx的
find(attrs={id=True, algin=None})        # 尋找有id屬性但是沒有algin屬性的


resp1 = soup.findAll('a', attrs = {'href': match1})
resp2 = soup.findAll('h1', attrs = {'class': match2})
resp3 = soup.findAll('img', attrs = {'id': match3})

text搜索
文字的搜索會(huì)導(dǎo)致其他搜索給的值如:tag, attrs都失效。方法與搜索tag一致

print p1.text
# u'This is paragraphone.'
print p2.text
# u'This is paragraphtwo.'
# 注意:1,每個(gè)tag的text包括了它以及它子孫的text。2,所有text已經(jīng)被自動(dòng)轉(zhuǎn)為unicode,如果需要,可以自行轉(zhuǎn)碼encode(xxx)

recursive和limit屬性
recursive=False表示只搜索直接兒子,否則搜索整個(gè)子樹,默認(rèn)為True。當(dāng)使用findAll或者類似返回list的方法時(shí),limit屬性用于限制返回的數(shù)量,如findAll('p', limit=2): 返回首先找到的兩個(gè)tag。

實(shí)例
本文以博客的文檔列表頁(yè)面為例,利用python對(duì)頁(yè)面中的文章名進(jìn)行提取。

文章列表頁(yè)中的文章列表部分的url如下:

<ul class="listing">
  <li class="listing-item"><span class="date">2014-12-03</span><a href="/post/linux_funtion_advance_feature" title="Linux函數(shù)高級(jí)特性" >Linux函數(shù)高級(jí)特性</a>
  </li>
  <li class="listing-item"><span class="date">2014-12-02</span><a href="/post/cgdb" title="cgdb的使用" >cgdb的使用</a>
  </li>
...
</ul>

代碼:

#!/usr/bin/env python                                                                              
# -*- coding: utf-8 -*-

' a http parse test programe '

__author__ = 'kuring lv'


import requests
import bs4

archives_url = "http://kuring.me/archive"

def start_parse(url) :
  print "開始獲取(%s)內(nèi)容" % url
  response = requests.get(url)
  print "獲取網(wǎng)頁(yè)內(nèi)容完畢"

  soup = bs4.BeautifulSoup(response.content.decode("utf-8"))
  #soup = bs4.BeautifulSoup(response.text);

  # 為了防止漏掉調(diào)用close方法,這里使用了with語(yǔ)句
  # 寫入到文件中的編碼為utf-8
  with open('archives.txt', 'w') as f :
    for archive in soup.select("li.listing-item a") :
      f.write(archive.get_text().encode('utf-8') + "\n")
      print archive.get_text().encode('utf-8')

# 當(dāng)命令行運(yùn)行該模塊時(shí),__name__等于'__main__'
# 其他模塊導(dǎo)入該模塊時(shí),__name__等于'parse_html'
if __name__ == '__main__' :
  start_parse(archives_url)

相關(guān)文章

最新評(píng)論