python获取网页标题title的几种方法代码

标签:
python网页标题title |
分类: 开源世界 |
# -*- coding:UTF-8 -*-
import urllib.request
import re
#url = 'http://bing.com'
url ='http://www.mengxi.net/book/263745/index.html'
page = urllib.request.urlopen(url,data = None)
html = page.read().decode('utf-8')
# or html=urllib.urlopen(url).read()
#print (html)
# Python3 findall数据类型用bytes类型
#方法1:无法读取包含\r\n\t的标题文本
title = re.findall(r'',html)
print (title)
#方法2:无法过滤换行符
con = re.findall(r'', html, re.S|re.M)
print (con)
#方法3
tag = 'title'
tag_pat = r'(?<=<'+ tag + '>).*?(?=</' + tag +
'>)'
tag_ex = re.compile(tag_pat, re.M|re.S)
tag_obj = re.search(tag_ex, html)
con = tag_obj.group()
print (con)
#运行情况如下:
#D:\Python34\works>py title.py
#[]
#['\r\n\t续蜀山剑侠传最新章节首家独发 - 风叶如笛 - 武侠仙侠 - 梦溪文学网\r\n']
#
#
续蜀山剑侠传最新章节首家独发 - 风叶如笛 - 武侠仙侠 - 梦溪文学网