Beautiful Soup 中文教程

2021-06-04 01:27:53 字數 2087 閱讀 5959

beautiful soup 是乙個處理python html/xml的模組,功能相當強勁,最近仔細的看了一下他的幫助文件,終於看明白了一些。 準備好好研究一下,順便將beautiful soup的一些用法整理一下,放到這個wiki上面,那個文件確實不咋地。

beautiful soup 中文教程

的官方頁面:

安裝其實很簡單,beautifulsoup

只有乙個檔案,只要把這個檔案拷到你的工作目錄,就可以了。

from

beautifulsoup

import

beautifulsoup

# for processing html

from

beautifulsoup

import beautifulstonesoup # for processing xml

import

beautifulsoup

# to get everything

beautifulsoup

物件需要一段html文字就可以建立了。

下面的**就建立了乙個beautifulsoup

物件:

from

beautifulsoup

import

beautifulsoup

doc = [

'', 'this is paragraphoneof ptyhonclub.org.',

'this is paragraphtwoof pythonclub.org.',

'']soup = beautifulsoup

(''.join

(doc)

)

beautifulsoup

可以直接用」.」訪問指定html元素

可以用 soup.html.head.title 得到title的name,和字串值。

>>> soup.html.head.title

pythonclub.org

>>> soup.html.head.title.name

u'title'

>>> soup.html.head.title.string

u'pythonclub.org'

>>>

也可以直接通過soup.title直接定位到指定html元素:

>>> soup.title

pythonclub.org

>>>

下面的例子給出了查詢含有」para」的html tag內容:

>>> soup.findall

(text=re.compile

("para"))

[u'this is paragraph ', u'this is paragraph '

]>>> soup.findall

(text=re.compile

("para"))

[0].parent

>this is paragraphoneof ptyhonclub.org.

>>> soup.findall

(text=re.compile

("para"))

[0].parent.contents

[u'this is paragraph ',one, u' of ptyhonclub.org.'

]

soup.findall

(id=re.compile

("para$"))

# [this is paragraphone.

,# this is paragraphtwo.] 

soup.findall

(attrs=

)# [this is paragraphone.

,# this is paragraphtwo.

]

BeautifulSoup 解析中文網頁亂碼問題

import urllib2 from beautifulsoup import beautifulsoup page urllib2.urlopen soup beautifulsoup page,fromencoding gb18030 print soup.originalencoding p...

BeautifulSoup常用方法

1.初始化 2.查詢指定標籤 eg 要找到符合的所有標籤 p.findall div 反覆利用標籤特徵可以找到最終需要的標籤 3.直接加標籤名可以找到所有子標籤 eg 找到所有標籤 p.td 4.直接以字典形式,可以訪問標籤內對應屬性的值 eg 要找到 中href 的值 www.csdn.net p...

BeautifulSoup學習筆記

prettify 將html 格式化 get text 獲得所有文字內容 contens 返回所有子節點 children 返回子節點生成器 descendants 返回所有子孫節點的生成器 strings 返回包含的多個字串的生成器 stripped strings 返回包含的多個字串 去除多餘空...