1. SGMLParser:

  这里定义了一个Parse类,继承SGMLParser里面的方法。使用一个变量is_h4做标记判定html文件中的h4标签,如果遇到h4标签,则将标签内的内容加入到Parse的变量name中。解释一下start_h4()和end_h4()函数,他们原型是SGMLParser中的

start_tagname(self, attrs)
end_tagname(self)

tagname就是标签名称,比如当遇到<h4>,就会调用start_h4,遇到</h4>,就会调用 end_h4。attrs为标签的参数,以[(attribute, value), (attribute, value), ...]的形式传回。

Demo:

 #!/usr/bin/python2.7
# FileName: sgmlparser.py
# Author: lxw
# Date: 2015-07-30 import urllib2
from sgmllib import SGMLParser class Parse(SGMLParser):
def __init__(self):
SGMLParser.__init__(self)
self.is_h4 = ""
self.name = []
self.is_a = ""
self.link = [] def start_h4(self, attrs):
self.is_h4 = 1 def end_h4(self):
self.is_h4 = "" def start_a(self, attrs):
self.is_a = 1 def end_a(self):
self.is_a = "" def handle_data(self, text):
if self.is_h4 == 1:
self.name.append(text)
if self.is_a == 1:
self.link.append(text) def main():
#content = urllib2.urlopen("https://kb.isc.org/").read()
content = urllib2.urlopen("https://list.taobao.com/browse/cat-0.htm").read()
parse = Parse()
parse.feed(content)
for item in parse.link:
print(item.decode("gbk").encode("utf-8"))
print("-"*20)
for item in parse.name:
print(item.decode("gbk").encode("utf-8")) if __name__ == '__main__':
main()
else:
print("Being imported as a module.")

2. PyQuery:

#!/usr/bin/python2.7
#coding=utf-8
#如果想有中文注释就必须得有上面的语句
# FileName: pyQueryParse.py
# Author: lxw
# Date: 2015-07-30 from pyquery import PyQuery
'''
直接运行没有问题, 但当把输出重定向到文件时, 就出现如下错误:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 166-167: ordinal not in range(128)
解决方法是增加下面的三行代码:
'''
import sys
reload(sys)
sys.setdefaultencoding("utf-8") def main():
source = PyQuery(url="https://list.taobao.com/browse/cat-0.htm")
#print(type(source)) #<class 'pyquery.pyquery.PyQuery'>
#print(type((source("a")))) #<class 'pyquery.pyquery.PyQuery'>
for data in source.find("a"):
#print(type(data)) #<class 'lxml.html.HtmlElement'>
#print(type(PyQuery((data)))) #<class 'pyquery.pyquery.PyQuery'>
#print(type(PyQuery(data).text())) #<type 'unicode'>/<type 'str'>
print(PyQuery(data).text()) if __name__ == '__main__':
main()
else:
print("Being imported as a module.")

References:

Python写爬虫——抓取网页并解析HTML

python数据抓取之pyquery包

Python HTML Resolution Demo - SGMLParser & PyQuery的更多相关文章

  1. RPi 2B python opencv camera demo example

    /************************************************************************************** * RPi 2B pyt ...

  2. Python爬虫利器六之PyQuery的用法

    前言 你是否觉得 XPath 的用法多少有点晦涩难记呢? 你是否觉得 BeautifulSoup 的语法多少有些悭吝难懂呢? 你是否甚至还在苦苦研究正则表达式却因为少些了一个点而抓狂呢? 你是否已经有 ...

  3. pyhanlp python 脚本的demo补充

    java demo https://github.com/hankcs/HanLP/tree/master/src/test/java/com/hankcs/demo github python de ...

  4. python爬虫(10)--PyQuery的用法

    简介 pyquery 可让你用 jQuery 的语法来对 xml 进行操作.这I和 jQuery 十分类似.如果利用 lxml,pyquery 对 xml 和 html 的处理将更快. 初始化 在这里 ...

  5. Python的网页解析库-PyQuery

    PyQuery库也是一个非常强大又灵活的网页解析库,如果你有前端开发经验的,都应该接触过jQuery,那么PyQuery就是你非常绝佳的选择,PyQuery 是 Python 仿照 jQuery 的严 ...

  6. Python简单多进程demo

    ''' 多线程使用场景: 怎样用Python的多线程提高效率? io操作不占用CPU 计算操作占用CPU Python多线程不适合CPU操作密集型的任务,适合io操作密集型的任务 如果有CPU操作密集 ...

  7. python - hadoop,mapreduce demo

    Hadoop,mapreduce 介绍 59888745@qq.com 大数据工程师是在Linux系统下搭建Hadoop生态系统(cloudera是最大的输出者类似于Linux的红帽), 把用户的交易 ...

  8. python ros topic demo

    发布者: #!/usr/bin/env python #coding=utf- import rospy from std_msgs.msg import String def talker():   ...

  9. 转 python trace walk DEMO

    https://blog.csdn.net/steadfast123/article/details/46965125 #quote from 'introduction to computation ...

随机推荐

  1. Ubuntu安装新版本nodejs的5种姿势

    引言: 写这篇文章之前,关于ubuntu14.04(Trusty)默认安装的NodeJS版本是0.10.25百思不解(什么鬼,哪一年的NodeJS) 写这篇文章之时,NodeJS的LTS版本号都已经1 ...

  2. git clone ....git

    [root@st153 git_test3]# git clone git@gitlab.gaobo.com:root/pythontest1.gitCloning into 'pythontest1 ...

  3. js定时器(执行一次、重复执行)

    代码如下: <script> //定时器 异步运行 function hello(){ alert("hello"); } //使用方法名字执行方法 var t1 = ...

  4. CI框架整合微信公共平台接口

    #CI框架控制器 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /*** CI框架整合微信 ...

  5. 什么是 Web?

    Web这个词刚开始显得有些泛泛,似乎“冲浪”.“网上存在”以及“主页”等等都和它拉上了一些关系. 甚至还有一种“Internet 综合症”的说法,对许多人狂热的上网行为提出了质疑.我们在这里有必要作一 ...

  6. .NET学习笔记(2)

    --在子页面设置模板页的图片: ( this.Master.FindControl(“imgHead”) as Image ).ImageUrl = “upload/image1.jpg” ; 文件的 ...

  7. (转)Unity笔记之编辑器(UnityEditor)

    在使用unity3d的过程中,时常会需要从场景中寻找或者调用一个对象,而Unity就提供了一个贴心的功能——拖拽.用鼠标拖一下中比写堆代码直观的多吧!但是Unity提供的远远不止这一丢丢,下面我们来简 ...

  8. Deep Networks for Image Super-Resolution with Sparse Prior

    深度学习中潜藏的稀疏表达 Deep Networks for Image Super-Resolution with Sparse Prior http://www.ifp.illinois.edu/ ...

  9. poj 1129(dfs+图的四色定理)

    题目链接:http://poj.org/problem?id=1129 思路:根据图的四色定理,最多四种颜色就能满足题意,使得相邻的两部分颜色不同.而最多又只有26个点,因此直接dfs即可. #inc ...

  10. poj 3084(最小割)

    题目链接:http://poj.org/problem?id=3084 思路:题目的意思是不让入侵者进入保护的房间,至少需要锁几道门.网络流建模:设一个超级源点,源点与有入侵者的房间相连,边容量为in ...