python 解析html中的link
来源:互联网 发布:云计算板块股票 编辑:程序博客网 时间:2024/06/18 17:17
htmllib.HTMLParser
#!/usr/bin/env pythonimport cStringIOimport formatterfrom htmllib import HTMLParserimport urlliburl = "http://blog.csdn.net/Lyq3413/article/details/76577465"user_name = "proxy_account"passwd = "proxy_pwd"proxy_base = "proxy.example.net:8080"proxy = "http://%s:%s@%s" % (user_name, passwd, proxy_base)proxies = {"http": proxy, "https": proxy}f = urllib.urlopen(url, proxies=proxies) #需要代理#f = urllib.urlopen(url) #不需要代理可以直接这么写data = f.read()f.close()parser = HTMLParser(formatter.AbstractFormatter( formatter.DumbWriter(cStringIO.StringIO())))parser.feed(data)parser.close()print parser.anchorlist
这段代码的工作方式中,最重要的是parser 类不进行I/O,它只处理一个formatter 对象。
Python 只有一个formatter 对象,即formatter.AbstractFormatter,用来解析数据并使用writer
对象来分配其输出内容。同样,Python 只有一个有用的writer 对象,即formatter.DumbWriter。
可以为该对象提供一个可选的文件对象,表示将输出写入文件。如果不提供这个文件对象,
则会写入标准输出,但后者一般不是所期望的。为了不让输出写到标准输出,先实例化一个
cStringIO 对象。StringIO 对象会吸收掉这些输出
HTMLParser.HTMLParser
from HTMLParser import HTMLParserfrom cStringIO import StringIOfrom urllib2 import urlopenimport urllib2from urlparse import urljoinurl = "http://blog.csdn.net/lyq3413/article/details/76577465"user_name = "proxy_account"passwd = "proxy_pwd"proxy = "http://%s:%s@proxy.example.net:8080" % (user_name, passwd)proxies = {"http": proxy, "https": proxy}proxy_handler = urllib2.ProxyHandler(proxies)opener = urllib2.build_opener(proxy_handler)urllib2.install_opener(opener)f = urlopen(url)data = StringIO(f.read())f.close()class AnchorParser(HTMLParser): def handle_starttag(self, tag, attrs): if tag != 'a': return if not hasattr(self, 'data'): self.data = [] for attr in attrs: if attr[0] == 'href': self.data.append(attr[1])parser = AnchorParser()parser.feed(data.read().decode('utf-8'))for link in parser.data: print urljoin(url, link)
BeautifulSoup
BeautifulSoup不是标准库需要单独安装
pip 工具安装:
$pip install BeautifulSoup
from BeautifulSoup import BeautifulSoup, SoupStrainerlinks = BeautifulSoup(data, parseOnlyThese=SoupStrainer('a'))
阅读全文
0 0
- python 解析html中的link
- <html:link 解析
- python 解析html标签中的属性
- python 正则表达式过滤文本中的html标签 源代码解析
- Python 通过 BeautifulSoup 将 html 中的表格解析成对象
- HTML - 头标签中的link使用
- 用python解析html
- 用python解析html
- 用python解析html
- python解析html/xml
- python HTML解析器
- python html解析
- python 解析html
- python 解析HTML
- Python 抓取解析HTML
- Python+lxml解析html
- python解析html tag
- Python解析HTML实例
- Leetcode算法学习日志-321 Burst Balloons
- shell脚本
- 如何处理高并发(详细)
- ZCMU新人训练赛A
- Linux性能测试 命令大全
- python 解析html中的link
- wanchain是个什么样的项目
- 多线程传参
- Ubuntu16.04+cuda8.0+cudnnV5.1配置faster-rcnn的方法
- 数据库的水平拆分和垂直拆分
- 剑指Offer_面试题18_树的子结构
- 前端 后端的基本 交互(后端 scala)(二)
- mcrypt加解密
- cgit安装