国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python使用BeautifulSoup庫解析HTML基本使用教程

2020-01-04 17:34:14
字體:
供稿:網(wǎng)友
這篇文章主要介紹了Python使用BeautifulSoup庫解析HTML基本使用教程,文中主要對其適合于制作爬蟲方面的特性進行了解析,需要的朋友可以參考下
 

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

準(zhǔn)備

1.Beautiful Soup安裝

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

執(zhí)行

sudo easy_install beautifulsoup4

即可安裝。

2.requests模塊的安裝

requests模塊用于加載要請求的web頁面。

在python的命令行中輸入import requests,報錯說明requests模塊沒有安裝。

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

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

 

基礎(chǔ)

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

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

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

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)容,返回對應(yīng)tag塊的剖析樹

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

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

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

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

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

    使用nextSibling, previousSibling獲取前后兄弟

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

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

4.find/findAll用法詳解
   函數(shù)原型:find(name=None, attrs={}, recursive=True, text=None, **kwargs),findAll會返回所有符合要求的結(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開頭的tagfind(lambda)            # 搜索函數(shù)返回結(jié)果為true的tag, 如:find(lambda name: if len(name) == 1) 搜索長度為1的tagfind(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搜索
文字的搜索會導(dǎo)致其他搜索給的值如:tag, attrs都失效。方法與搜索tag一致

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

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

實例
本文以博客的文檔列表頁面為例,利用python對頁面中的文章名進行提取。

文章列表頁中的文章列表部分的url如下:

<ul class="listing">  <li class="listing-item"><span class="date">2014-12-03</span><a href="/post/linux_funtion_advance_feature"  </li>  <li class="listing-item"><span class="date">2014-12-02</span><a href="/post/cgdb"  </li>...</ul>

代碼:

#!/usr/bin/env python                                                                              # -*- coding: utf-8 -*-' a http parse test programe '__author__ = 'kuring lv'import requestsimport bs4archives_url = "http://kuring.me/archive"def start_parse(url) :  print "開始獲取(%s)內(nèi)容" % url  response = requests.get(url)  print "獲取網(wǎng)頁內(nèi)容完畢"  soup = bs4.BeautifulSoup(response.content.decode("utf-8"))  #soup = bs4.BeautifulSoup(response.text);  # 為了防止漏掉調(diào)用close方法,這里使用了with語句  # 寫入到文件中的編碼為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)命令行運行該模塊時,__name__等于'__main__'# 其他模塊導(dǎo)入該模塊時,__name__等于'parse_html'if __name__ == '__main__' :  start_parse(archives_url)

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 天全县| 安宁市| 新邵县| 达州市| 鹿泉市| 错那县| 江阴市| 昌吉市| 惠州市| 根河市| 保靖县| 泸水县| 泰宁县| 曲松县| 宜兰县| 邹城市| 彭阳县| 旬邑县| 新竹县| 会昌县| 太仓市| 崇左市| 嘉善县| 讷河市| 阿坝县| 丰城市| 潜山县| 石城县| 镇雄县| 太和县| 嘉兴市| 梓潼县| 攀枝花市| 临泉县| 桦甸市| 普洱| 万载县| 禹城市| 西城区| 漳平市| 观塘区|