lxml 功能強大, 不過提供太多 API, 不太容易在官網找資料 (或是我太沒耐性吧...)。記錄一下抓網站取內容常用的 code snippet:
下載網頁內容轉成 lxml.html 的 Element object
import sys
import requests
import lxml.html
DEBUG = False
def get_web_content(link):
if not link:
return None, lxml.html.fromstring(u'<html></html>')
try:
r = requests.get(link)
try:
content = r.content.decode('UTF-8')
except UnicodeDecodeError, ude:
if DEBUG:
msg = (
'The content is not in UTF-8 (ude=%s). '
'Try ISO-8859-1 instead.\n' % ude )
sys.stderr.write(msg)
# Try another encoding. If fail, just let it fail.
content = r.content.decode('ISO-8859-1')
if DEBUG:
sys.stderr.write('Get content of link %s: %s\n' % (link, content[:50]))
return r.status_code, lxml.html.fromstring(content)
except Exception, e:
if DEBUG:
sys.stderr.write('Fail to get content of link: %s (e=%s)\n' % (link, e))
return None, lxml.html.fromstring(u'<html></html>')
使用 cssselect 取值
取得 lxml.html Element 後, 用 cssselect() 和 CSS path 可輕鬆取值。剩下的就是在 ipython 上試 API, 看怎麼操作 Element 物件, 這樣比看文件快。
沒有留言:
張貼留言