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

下面是结果:

百度一下,你就知道

百度一下,你就知道

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

以上这篇python抽取指定url页面的title方法就是小编分享给大家的全部内容了,希望能给大家一个参考

python抽取指定url页面的title方法的更多相关文章

  1. Python+Selenium学习--打印当前页面的title及url

    场景 测试中,访问1个页面然后判断其title是否符合预期是很常见的1个用例,所谓用例不够,title来凑就是这个道理.更具体一点,假设1个页面的title应该是'hello world', 那么可以 ...

  2. 转载: js jquery 获取当前页面的url,获取frameset中指定的页面的url(有修改)

    转载网址:http://blog.csdn.net/bestlxm/article/details/6800077 js jquery 怎么获取当前页面的url,获取frameset中指定的页面的ur ...

  3. Vue设置页面的title

    原文地址:http://www.cnblogs.com/JimmyBright/p/7410771.html 前端框架如Vue.React等都是单页面的应用,也就是说整个web站点其实都是一个inde ...

  4. JS魔法堂:定义页面的Dispose方法——[before]unload事件启示录

    前言  最近实施的同事报障,说用户审批流程后直接关闭浏览器,操作十余次后系统就报用户会话数超过上限,咨询4A同事后得知登陆后需要显式调用登出API才能清理4A端,否则必然会超出会话上限.  即使在页面 ...

  5. 定义页面的Dispose方法:[before]unload事件启示录

    前言 最近实施的同事报障,说用户审批流程后直接关闭浏览器,操作十余次后系统就报用户会话数超过上限,咨询4A同事后得知登陆后需要显式调用登出API才能清理4A端,否则必然会超出会话上限. 即使在页面上增 ...

  6. 提交(post)xml文件给指定url的2种方法

    原文:提交(post)xml文件给指定url的2种方法 1  这段代码是在网上搜到的,拿来共享,项目正好要用到.其中的data你只需要传递一个xml字符串就可以 protected   string  ...

  7. 使用vue-router设置每个页面的title

    进入 router 文件夹底下的index.js文件 首先引入: import Vue from 'vue' import Router from 'vue-router' 然后在路由里面配置每个路由 ...

  8. 获取页面的title值

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. 调用上一个页面的js方法

    点击商品分类,弹出下框 点击确定,将选中的类别的name和唯一的code返回到上个页面 function save(){ var ids = getIdSelections(); jp.get(&qu ...

随机推荐

  1. 【转】ufw 端口

    1.扫描端口 用ubuntu自带的网络工具中的端口扫描不够强大,扫描结果可能不全,推荐用nmap,黑客常用的端口扫描利器!安装方法:sudo apt-get install nmap ,想扫描端口nm ...

  2. No PostCSS Config found in报错解决

    前情提要]日前本人将本地项目上传GitHub之后,然后再clone到本地,运行是报错:Error: No PostCSS Config found in... 项目在本地打包运行的时候不报错,上传到 ...

  3. 【python】使用plotly生成图表数据

    安装 在 ubuntu 环境下,安装 plotly 很简单 python 版本2.7+ pip install plotly 绘图 在 plotly 网站注册后,可以直接将生成的图片保存到网站上,便于 ...

  4. JavaScript中数组的排序——sort()

    数组排序sort() sort()方法使数组中的元素按照一定的顺序排列. arrayObject.sort(方法函数) 1.如果不指定<方法函数>,则按unicode码顺序排列. 2.如果 ...

  5. canvas制图学习

    <!DOCTYPE html> <html lang="zh-en"> <head> <meta charset="UTF-8& ...

  6. SVG矢量绘图 path路径详解(贝塞尔曲线及平滑)

    以二次贝塞尔曲线的公式为例: js函数: //p0.p1.p2三个点,其中p0为起点,p2为终点,p1为控制点 //它们的坐标用数组表示[x,y] //t的范围是0-1 function qBerzi ...

  7. Codeforces Round #543 (Div. 1, based on Technocup 2019 Final Round) 题解

    题面戳这里 A. Diana and Liana 首先如果s>ks>ks>k一定无解,特判一下.那么我们考虑找恰好满足满足题目中的要求的区间[l,r][l,r][l,r],那么需要要 ...

  8. Codeforces Round #429 (Div. 2/Div. 1) [ A/_. Generous Kefa ] [ B/_. Godsend ] [ C/A. Leha and Function ] [ D/B. Leha and another game about graph ] [ E/C. On the Bench ] [ _/D. Destiny ]

    PROBLEM A/_ - Generous Kefa 题 OvO http://codeforces.com/contest/841/problem/A cf 841a 解 只要不存在某个字母,它的 ...

  9. 023_统计当前 Linux 系统中可以登录计算机的账户有多少个

    #!/bin/bash #方法 1: grep "bash$" /etc/passwd | wc -l #方法 2: #-F END都要大写! awk -F: '/bash$/{x ...

  10. [Luogu] 网络

    https://www.luogu.org/problemnew/show/P3250 树链剖分 + 线段树 + 优先队列 要求未被影响的请求中最大的 所以每次将每条路径在整棵树上的补集的每个节点的优 ...