分类: python2012-02-02 21:45697人阅读评论(0)收藏举报
目录(?)[+]
取得html檔
在python可以很輕易的用urllib來達成
webfile = urllib.urlopen(url)
讀取內容可以用
webcontext = wefbfile.read()orwebcontext = webfile.read().decode("UTF-8")
如果不指定decode方式則以系統預設方式decode
交由BeautifulSoup處理
soup = BeautifulSoup.BeautifulStoneSoup(webcontext)
此時soup為html(<html></html>節點)或xml的root node
在html可以用soup = soup.body移至<head>節點上
使用soup = soup.nextSibling可以將point移至<body>上
可以利用這些數狀結構的操作在tree裡面移動

以CSS樣式來存取node
以上方式當檔案在結構上有些問題的時候就會出問題
所以可以利用findAll的方式直接去存取想要的node
htmldata = soup.findAll("p", {"class" : "right"})
尋找所有<p></p>的node並return一個list給htmldata變數
以屬性方式存取node
htmltitle = soup.findAll(id = "title")
尋找所有<XX id = "title"></XX>的node(XX為任意名稱)
取得node裡的內容
取得屬性
想取得像href這類超連結時可用(以下為soup指到<a>node情況下)
url = soup['href']取得內容
如果是<node>string</node>的情況下可以使用
context = soup.string
如果要取得所有內容的話,可使用
plist = soup.contents
把所有內容都存入plist內
基本上使用上面這些技巧就能應付一般需求了
中文文档:
http://www.crummy.com/software/BeautifulSoup/documentation.zh.html