之前用原生的HTMLParser用到很囧
感覺功能還是不夠強大

後來看到了BautifulSoup這個plugin就想說用用看
使用很方便 只要把裏面的BeautifulSoup複製一份到自己的目錄下
然後import進來就好了

import BeautifulSoup

在Google app engine裡
我是搭配urlfetch來使用
如以下的片段範例

from google.appengine.api import urlfetch
from BeautifulSoup import BeautifulSoup
url = 'the url address you want'
result = urlfetch.fetch(url) #抓網頁
if result.status_code == 200:
   book = result.content  # book 會得到html的內容
   soup = BeautifulSoup(book, fromEncoding="utf-8") #建立一個BeautifulSoup的物件
   book = soup.findAll('div',{'id':'content'})

結果會抓出包含 div id=content的內容, findAll會回傳一個list,
所以在Django的template裡需要用for loop來把book的內容印出來
如果要利用str(book)轉成字串, 需要注意頭尾的'['和']', 以及中間用來分開裏面元素的','

arrow
arrow
    文章標籤
    python django
    全站熱搜

    卡卡 發表在 痞客邦 留言(0) 人氣()