码迷,mamicode.com
首页 > 编程语言 > 详细

【python】使用HTMLParser、cookielib抓取和解析网页、从HTML文档中提取链接、图像、文本、Cookies

时间:2015-12-09 16:49:59      阅读:556      评论:0      收藏:0      [点我收藏+]

标签:

一、从HTML文档中提取链接

模块HTMLParser,该模块使我们能够根据HTML文档中的标签来简洁、高效地解析HTML文档。

处理HTML文档的时候,我们常常需要从其中提取出所有的链接。使用HTMLParser模块后,这项任务将变得易如反掌。首先,我们需要定义 一个新的HTMLParser类,以覆盖handle_starttag()方法,我们将使用这个方法来显示所有标签的HRef属性值。

定义好新的HTMLParser类之后,需要创建一个实例来返回HTMLParser对象。然后,就可以使用urllib.urlopen(url)打开HTML文档并读取该HTML文件的内容了。

为了解析HTML文件的内容并显示包含其中的链接,可以使用read()函数将数据传递给HTMLParser对象。HTMLParser对象 的feed函数将接收数据,并通过定义的HTMLParser对象对数据进行相应的解析。需要注意,如果传给HTMLParser的feed()函数的数 据不完整的话,那么不完整的标签会保存下来,并在下一次调用feed()函数时进行解析。当HTML文件很大,需要分段发送给解析器的时候,这个功能就会 有用武之地了。下面是一个具体的例子。

# -*- coding: UTF-8 -*-
__author__ = ‘paul‘
import HTMLParser
import urllib
import sys
#定义HTML解析器
class parseLinks(HTMLParser.HTMLParser):
    def handle_starttag(self, tag, attrs):
        if tag == ‘a‘:##显示标签为a
            for name,value in attrs:
                if name == ‘href‘:#显示属性为href
                    print value##显示标签属性值
                    print self.get_starttag_text()##全部显示
#创建HTML解析器的实例
lParser = parseLinks()
#打开HTML文件
lParser.feed(urllib.urlopen( "http://www.python.org/index.html").read())
lParser.close()

二、从HTML文档中提取图像

定义好新的HTMLParser类之后,需要创建一个实例来返回HTMLParser对象。然后,就可以使用urllib.urlopen(url)打开HTML文档并读取该HTML文件的内容了。

为了解析HTML文件的内容并显示包含其中的图像,可以使用feed(data)函数将数据发送至HTMLParser对象。HTMLParser对象的feed函数将接收数据,并通过定义的HTMLParser对象对数据进行相应的解析。下面是一个具体的示例:

# -*- coding: UTF-8 -*-
__author__ = ‘paul‘
import HTMLParser
import urllib
import sys
urlString = "http://www.python.org"
#urlString = "http://www.baidu.com"
#把图像文件保存至硬盘
def getImage(addr):
    u = urllib.urlopen(addr)
    data = u.read()
    splitPath = addr.split(‘/‘)
    fName = splitPath.pop()
    print "Saving %s" % fName
    f = open(fName, ‘wb‘)
    f.write(data)
    f.close()
    #定义HTML解析器
class parseImages(HTMLParser.HTMLParser):
    def handle_starttag(self, tag, attrs):
        if tag == ‘img‘:
            for name,value in attrs:
                if name == ‘src‘:
                    #value1=value[2:]
                    #print value1
                    print self.get_starttag_text()
                    getImage(urlString + "/" + value)##当图片的src为相对路径时需要拼接
                    #getImage("http://"+value1)##当图片的src为相对路径时,直接使用绝对路径即可,但是需要注意的是,urllib.urlopen需要添加链接的协议如http://或者https://等等
#创建HTML解析器的实例
lParser = parseImages()
#打开HTML文件
u = urllib.urlopen(urlString)
print "Opening URL/n===================="
print u.info()
#把HTML文件传给解析器
lParser.feed(u.read())
lParser.close()

 三、从HTML文档中提取文本

  处理HTML文档的时候,我们常常需要从其中提取出所有的文本。使用HTMLParser模块后,这项任务将变得非常简单了。首先,我们需要定义一个新的HTMLParser类,以覆盖handle_data()方法,该方法是用来解析并文本数据的。

# -*- coding: UTF-8 -*-
__author__ = ‘paul‘
import HTMLParser
import urllib
urlText = []
#定义HTML解析器
class parseText(HTMLParser.HTMLParser):
    def handle_data(self, data):
        if data != ‘/n‘:
            urlText.append(data)
#创建HTML解析器的实例
lParser = parseText()
#把HTML文件传给解析器
lParser.feed(urllib.urlopen( "http://www.baidu.com").read())
lParser.close()
for item in urlText:
    print item

 四、从HTML文档中提取Cookies

为了从HTML文档提取cookies,首先得使用cookielib模块的LWPCookieJar()函数创建一个cookie jar的实例。LWPCookieJar()函数将返回一个对象,该对象可以从硬盘加载Cookie,同时还能向硬盘存放Cookie。

  接下来,使用urllib2模块的build_opener([handler, . . .])函数创建一个opener对象,当HTML文件打开时该对象将处理cookies。函数build_opener可以接收零个或多个处理程序(这些 程序将按照它们被指定的顺序连接在一起)作为参数并返回一个。

  注意,如果想让urlopen()使用opener对象来打开HTML文件的话,可以调用install_opener(opener)函数,并将opener对象传给它。否则,请使用opener对象的open(url)函数来打开HTML文件。

  一旦已经创建并安装了opener对象,就可以使用urllib2模块中的Request(url)函数来创建一个Request对象,然后就能使用urlopen(Request)函数来打开HTML文件了。

  打开HTML页面后,该页面的所有Cookie将被存放到LWPCookieJar对象中,之后,您可以使用LWPCookieJar对象的save(filename)函数了。

# -*- coding: UTF-8 -*-
__author__ = ‘paul‘
import os
import urllib2
import cookielib
from urllib2 import urlopen, Request
cookieFile = "cookies.dat"
testURL = ‘http://www.baidu.com/‘
#为cookie jar 创建实例
cJar = cookielib.LWPCookieJar()
#创建HTTPCookieProcessor的opener对象
opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cJar))
#安装HTTPCookieProcessor的opener
urllib2.install_opener(opener)
#创建一个Request对象
r = Request(testURL)
#打开HTML文件
h = urlopen(r)
print "页面的头部/n======================"
print h.info()
print "页面的Cookies/n======================"
print cJar
for ind, cookie in enumerate(cJar):
    print "%d - %s" % (ind, cookie)
    #保存cookies
    cJar.save(cookieFile)

五、为HTML文档中的属性值添加引号

# -*- coding: UTF-8 -*-
__author__ = ‘paul‘
import HTMLParser
import urllib
import sys
#定义HTML解析器
class parseAttrs(HTMLParser.HTMLParser):
    def init_parser (self):
        self.pieces = []
    def handle_starttag(self, tag, attrs):
        fixedAttrs = ""
    #for name,value in attrs:
        for name, value in attrs:
            fixedAttrs += "%s=\"%s\" " % (name, value)
            self.pieces.append("<%s %s>" % (tag, fixedAttrs))
    def handle_charref(self, name):
        self.pieces.append("&#%s;" % (name))
    def handle_endtag(self, tag):
        self.pieces.append("%s" % (tag))
    def handle_entityref(self, ref):
        self.pieces.append("&%s" % (ref))
    def handle_data(self, text):
        self.pieces.append(text)
    def handle_comment(self, text):
        self.pieces.append("s%" % (text))
    def handle_pi(self, text):
        self.pieces.append("s%"% (text))
    def handle_decl(self, text):
        self.pieces.append("s%" % (text))
    def parsed (self):
        return "".join(self.pieces)
#创建HTML解析器的实例
attrParser = parseAttrs()
#初始化解析器数据
attrParser.init_parser()
#把HTML文件传给解析器
attrParser.feed(urllib.urlopen("test2.html").read())
#显示原来的文件内容
print "原来的文件/n========================"
print open("test2.html").read()
#显示解析后的文件
print "解析后的文件/n========================"
print attrParser.parsed()
attrParser.close()

  

 

【python】使用HTMLParser、cookielib抓取和解析网页、从HTML文档中提取链接、图像、文本、Cookies

标签:

原文地址:http://www.cnblogs.com/paulwinflo/p/5033092.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!