对html的解析是网页抓取的基础,分析抓取的结果找到自己想要的内容或标签以达到抓取的目的。
HTMLParser是python用来解析html的模块。它可以分析出html里面的标签、数据等等,是一种处理html的简便途径。 HTMLParser采用的是一种事件驱动的模式,当HTMLParser找到一个特定的标记时,它会去调用一个用户定义的函数,以此来通知程序处理。它主要的用户回调函数的命名都是以handler_开头的,都是HTMLParser的成员函数。当我们使用时,就从HTMLParser派生出新的类,然后重新定义这几个以handler_开头的函数即可。这几个函数包括:
- handle_startendtag 处理开始标签和结束标签
- handle_starttag 处理开始标签,比如<xx>
- handle_endtag 处理结束标签,比如</xx>
- handle_charref 处理特殊字符串,就是以&#开头的,一般是内码表示的字符
- handle_entityref 处理一些特殊字符,以&开头的,比如
- handle_data 处理数据,就是<xx>data</xx>中间的那些数据
- handle_comment 处理注释
- handle_decl 处理<!开头的,比如<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
- handle_pi 处理形如<?instruction>的东西
1. 基本解析,找到开始和结束标签
from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print("Encountered the beginning of a %s tag" %(tag)) def handle_endtag(self, tag): print ("Encountered the end of a %s tag" %(tag)) if __name__ == '__main__': a = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><!--insert javaScript here!--><title>test</title><body><a href="http: //www.163.com">链接到163</a></body></html>' m = MyHTMLParser() #传入要分析的html模块 m.feed(a)
运行结果
Encountered the beginning of a html tag
Encountered the beginning of a head tag
Encountered the beginning of a title tag
Encountered the end of a title tag
Encountered the beginning of a body tag
Encountered the beginning of a a tag
Encountered the end of a a tag
Encountered the end of a body tag
Encountered the end of a html tag
Encountered the beginning of a head tag
Encountered the beginning of a title tag
Encountered the end of a title tag
Encountered the beginning of a body tag
Encountered the beginning of a a tag
Encountered the end of a a tag
Encountered the end of a body tag
Encountered the end of a html tag
2. 解析html的超链接和链接显示的内容
from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.flag=None def handle_starttag(self, tag, attrs): # 这里重新定义了处理开始标签的函数 if tag == 'a': # 判断标签<a>的属性 self.flag='a' for name,value in attrs: if name == 'href': print("href:"+value) def handle_data(self,data): if self.flag == 'a': print("data:"+data) if __name__ == '__main__': a = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><!--insert javaScript here!--><title>test</title><body><a href="http: //www.163.com">链接到163</a></body></html>' my = MyHTMLParser() my.feed(a)
运行结果
href:http: //www.163.com
data:链接到163
data:链接到163
3. 完整解析html元素,拼接后原样输出
from html.parser import HTMLParser import html.entities class BaseHTMLProcessor(HTMLParser): def reset(self): # extend (called by HTMLParser.__init__) self.pieces = [] HTMLParser.reset(self) def handle_starttag(self, tag, attrs): # called for each start tag # attrs is a list of (attr, value) tuples # e.g. for <pre class="screen">, tag="pre", attrs=[("class", "screen")] # Ideally we would like to reconstruct original tag and attributes, but # we may end up quoting attribute values that weren't quoted in the source # document, or we may change the type of quotes around the attribute value # (single to double quotes). # Note that improperly embedded non-HTML code (like client-side Javascript) # may be parsed incorrectly by the ancestor, causing runtime script errors. # All non-HTML code must be enclosed in HTML comment tags (<!-- code -->) # to ensure that it will pass through this parser unaltered (in handle_comment). strattrs = "".join([' %s="%s"' % (key, value) for key, value in attrs]) self.pieces.append("<%(tag)s%(strattrs)s>" % locals()) def handle_endtag(self, tag): # called for each end tag, e.g. for </pre>, tag will be "pre" # Reconstruct the original end tag. self.pieces.append("</%(tag)s>" % locals()) def handle_charref(self, ref): # called for each character reference, e.g. for " ", ref will be "160" # Reconstruct the original character reference. self.pieces.append("&#%(ref)s;" % locals()) def handle_entityref(self, ref): # called for each entity reference, e.g. for "©", ref will be "copy" # Reconstruct the original entity reference. self.pieces.append("&%(ref)s" % locals()) # standard HTML entities are closed with a semicolon; other entities are not if entities.entitydefs.has_key(ref): self.pieces.append(";") def handle_data(self, text): # called for each block of plain text, i.e. outside of any tag and # not containing any character or entity references # Store the original text verbatim. self.pieces.append(text) def handle_comment(self, text): # called for each HTML comment, e.g. <!-- insert Javascript code here --> # Reconstruct the original comment. # It is especially important that the source document enclose client-side # code (like Javascript) within comments so it can pass through this # processor undisturbed; see comments in unknown_starttag for details. self.pieces.append("<!--%(text)s-->" % locals()) def handle_pi(self, text): # called for each processing instruction, e.g. <?instruction> # Reconstruct original processing instruction. self.pieces.append("<?%(text)s>" % locals()) def handle_decl(self, text): # called for the DOCTYPE, if present, e.g. # <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" # "http://www.w3.org/TR/html4/loose.dtd"> # Reconstruct original DOCTYPE self.pieces.append("<!%(text)s>" % locals()) def output(self): """Return processed HTML as a single string""" return "".join(self.pieces) if __name__ == '__main__': a = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><!--insert javaScript here!--><title>test</title><body><a href="http: //www.163.com">链接到163</a></body></html>' bhp =BaseHTMLProcessor() bhp.feed(a) print(bhp.output())
运行结果
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><!--insert javaScript here!--><title>test</title><body><a href="http: //www.163.com">链接到163</a></body></html>
相关推荐
本文实例讲述了Python实现抓取网页生成Excel文件的方法。分享给大家供大家参考,具体如下: Python抓网页,主要用到了PyQuery,这个跟jQuery用法一样,超级给力 示例代码如下: #-*- encoding:utf-8 -*- import sys...
该库旨在尽可能简单直观地解析HTML(例如,抓取网页)
本文将介绍如何使用Python抓取网页数据并解析。 1. Python抓取网页数据的基本流程 首先,我们需要明确一下Python抓取网页数据的基本流程。通常情况下,我们需要完成以下三个步骤: (1)发送HTTP请求获取网页数据...
第一部分重点介绍网络抓取机制:使用 Python 从网络服务器请求信息,对服务器响应进行基本处理,并以自动方式与网站交互。第二部分探讨了各种更具体的工具和应用程序,以适应您可能遇到的任何网络抓取场景。 解析...
学习python一周,学着写了一个爬虫,用来抓取360百科的词条,在这个过程中,由于一个小小的改动,程序出现一些问题,又花了几天时间研究,问了各路高手,都没解决,最终还是自己解决了,其实就是对list列表理解不够...
一个实验,看看如何使用request-html来抓取和解析单页网站,它使用了一个完整的Web浏览器来抓取这些网站。
此资源是一个基于Python的爬虫脚本,利用urllib库抓取指定贴吧的指定页数据,并将抓取到的内容保存到本地文件中。该脚本可以帮助用户快速获取贴吧中的帖子标题、内容、发布时间等信息,并可以用于数据分析、内容提取...
爬虫通常由搜索引擎、数据挖掘工具、监测系统等应用于网络数据抓取的场景。 爬虫的工作流程包括以下几个关键步骤: URL收集: 爬虫从一个或多个初始URL开始,递归或迭代地发现新的URL,构建一个URL队列。这些URL...
网页解析器有正则表达式(直观,将网页转成字符串通过模糊匹配的方式来提取有价值的信息,当文档比较复杂的时候,该方法提取数据的时候就会非常的困难)、html.parser(Python自带的)、beautifulsoup(第三方插件,...
我们知道,Python拥有出色的内置HTML解析器模块——HTMLParser,然而还有一个功能更为强大的HTML或XML解析工具——BeautifulSoup(美味的汤),它是一个第三方库。简单来说,BeautifulSoup最主要的功能是从网页抓取...
Beautiful Soup:Beautiful Soup是一个HTML/XML解析库,能够从网页中提取数据,并提供了简单易用的API操作。它适合用于静态网页的解析和数据提取。 Requests:Requests是一个Python HTTP库,可以方便地发送HTTP请求...
一个Python模块用于抓取几个搜索引擎bd,gg,soso 实现一个Python模块用于抓取几个搜索引擎,可以按照以下概念进行设计: 1. **搜索引擎选择:** 选择几个目标搜索引擎,如Google、Bing、Baidu等。 2. **构建搜索...
使用python将网页抓取下来之后,下一步我们就应该解析网页,提取我们所需要的内容了,在python里提供了一个简单的解析模块HTMLParser类,使用起来也是比较简单的,解析语法没有用到XPath类似的简洁模式,但新手用...
其中,使用BeautifulSoup来解析HTML,可以参考我的另外一篇文章:Windows8下安装BeautifulSoup 代码如下: 复制代码 代码如下: __author__ = ‘曾是土木人’ # -*- coding: utf-8 -*- #采集SERP搜索结果标题 import ...
在这个教程中,我们将以爬取百度首页为例,介绍如何使用Python语言进行简单的网页数据抓取。 本教程主要分为四个部分: 导入所需库:介绍了在爬虫程序中需要使用的Python库,包括requests库(用于向网站发送HTTP...
抓取网页数据的思路有好多种,一般有:直接代码请求http、模拟浏览器请求数据(通常需要登录验证)、控制浏览器实现数据抓取等。这篇不考虑复杂情况,放一个读取简单网页数据的小例子: 目标数据 将ittf网站上这个...
这段代码是一个简单的Python爬虫程序,用于从指定...这个程序的主要用途是从一个指定的网页抓取并输出其标题和第一个段落的内容。这可以用于简单的网页数据提取,例如新闻网站、博客或任何其他有标题和段落文本的网站。
通过Python语言提供的各种模块,我们无需借助Web服务器或者Web浏览器就能够解析和处理HTML文档。本文将详细介绍如何利用Python抓取和解析网页
给定一些示例网页和要提取的数据,就为所有相似的页面构建一个解析器。 概述Scrapinghub wr Scrapely Scrapely是一个用于从HTML页面提取结构化数据的库。 给定一些示例网页和要提取的数据,就为所有相似的页面构建一...
爬虫是一种从网站上抓取大量数据的自动化方法。即使是复制和粘贴你喜欢的网站上的引用或行,也是一种web抓取的形式。大多数网站不允许你保存他们网站上的数据供你使用。因此,唯一的选择是手动复制数据,这将消耗...