python抽取指定url页面的title方法-创新互联

今天简单使用了一下python的re模块和lxml模块,分别利用的它们提供的正则表达式和xpath来解析页面源码从中提取所需的title,xpath在完成这样的小任务上效率非常好,在这里之所以又使用了一下正则表达式是因为xpath在处理一些特殊的页面的时候会出现乱码的情况,当然这不是xpath的原因,而是页面本身编码,跟utf-8转码之间有冲突所致,这里看代码:

公司主营业务:成都网站建设、成都网站制作、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。成都创新互联是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。成都创新互联推出左贡免费做网站回馈大家。
# !/usr/bin/python
#-*-coding:utf-8-*-
'''
功能:抽取指定url的页面内容中的title
'''
import re
import chardet
import urllib
from lxml import etree
def utf8_transfer(strs):
 '''
 utf8编码转换
 '''
 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抽取网页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抽取网页Title
 '''
 Html = utf8_transfer(Html)
 compile_rule = ur'.*'
 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

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网站标题:python抽取指定url页面的title方法-创新互联
网站URL:http://myzitong.com/article/dieeec.html