python抽取指定url頁面的title方法
今天簡單使用了一下python的re模塊和lxml模塊,分別利用的它們提供的正則表達式和xpath來解析頁面源碼從中提取所需的title,xpath在完成這樣的小任務(wù)上效率非常好,在這里之所以又使用了一下正則表達式是因為xpath在處理一些特殊的頁面的時候會出現(xiàn)亂碼的情況,當然這不是xpath的原因,而是頁面本身編碼,跟utf-8轉(zhuǎn)碼之間有沖突所致,這里看代碼:
# !/usr/bin/python
#-*-coding:utf-8-*-
'''
功能:抽取指定url的頁面內(nèi)容中的title
'''
import re
import chardet
import urllib
from lxml import etree
def utf8_transfer(strs):
'''
utf8編碼轉(zhuǎn)換
'''
try:
if isinstance(strs, unicode):
strs = strs.encode('utf-8')
elif chardet.detect(strs)['encoding'] == 'GB2312':
strs = strs.decode("gb2312", 'ignore').encode('utf-8')
elif chardet.detect(strs)['encoding'] == 'utf-8':
strs = strs.decode('utf-8', 'ignore').encode('utf-8')
except Exception, e:
print 'utf8_transfer error', strs, e
return strs
def get_title_xpath(Html):
'''
用xpath抽取網(wǎng)頁Title
'''
Html = utf8_transfer(Html)
Html_encoding = chardet.detect(Html)['encoding']
page = etree.HTML(Html, parser=etree.HTMLParser(encoding=Html_encoding))
title = page.xpath('/html/head/title/text()')
try:
title = title[0].strip()
except IndexError:
print 'Nothing'
print title
def get_title(Html):
'''
用re抽取網(wǎng)頁Title
'''
Html = utf8_transfer(Html)
compile_rule = ur'<title>.*</title>'
title_list = re.findall(compile_rule, Html)
if title_list == []:
title = ''
else:
title = title_list[0][7:-8]
print title
if __name__ == '__main__':
url = 'http://www.baidu.com'
html = urllib.urlopen(url).read()
new_html = utf8_transfer(html)
try:
get_title_xpath(new_html)
get_title(new_html)
except Exception, e:
print e
下面是結(jié)果:
百度一下,你就知道
百度一下,你就知道
簡單的小實踐,繼續(xù)學習,歡迎交流。
以上這篇python抽取指定url頁面的title方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python中ImageTk.PhotoImage()不顯示圖片卻不報錯問題解決
這篇文章主要給大家介紹了關(guān)于在python中ImageTk.PhotoImage()不顯示圖片卻不報錯問題的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-12-12

