python抽取指定url页面的title方法

yipeiwu_com5年前Python基础

今天简单使用了一下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>.*</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

下面是结果:

百度一下,你就知道
百度一下,你就知道

简单的小实践,继续学习,欢迎交流。

以上这篇python抽取指定url页面的title方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python opencv 图像拼接的实现方法

python opencv 图像拼接的实现方法

初级的图像拼接为将两幅图像简单的粘贴在一起,仅仅是图像几何空间的转移与合成,与图像内容无关。高级图像拼接也叫作基于特征匹配的图像拼接,拼接时消去两幅图像相同的部分,实现拼接合成全景图。...

Python中的闭包详细介绍和实例

一、闭包 来自wiki: 闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数。这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它...

使用python实现ANN

使用python实现ANN

本文实例为大家分享了python实现ANN的具体代码,供大家参考,具体内容如下 1.简要介绍神经网络 神经网络是具有适应性的简单单元组成的广泛并行互联的网络。它的组织能够模拟生物神经系统...

使用Python神器对付12306变态验证码

使用Python神器对付12306变态验证码

临近春节,【听图阁-专注于Python设计】小编带领大家用Python抢火车票! 首先我们需要splinter 安装: pip install splinter -i http://py...

Pandas之Dropna滤除缺失数据的实现方法

约定: import pandas as pd import numpy as np from numpy import nan as NaN 滤除缺失数据 pandas的设计目...