`
sdu_wizard
  • 浏览: 98772 次
  • 性别: Icon_minigender_1
  • 来自: 亚特兰蒂斯
社区版块
存档分类
最新评论

Python抓取百度热搜词

阅读更多
最近在学习python,就写了个很简单的抓取百度热搜词的小代码。

百度新闻页面(http://news.baidu.com/)上的百度热搜词部分的html是这个样子的

<a href="http://news.baidu.com/ns?cl=3&ct=9&rn=20&sp=hotquery&word=%C1%F5%CF%E8%20%BB%D8%B9%FA" target="_blank" mon="ct=1&a=30">刘翔回国</a>

直接用正则进行匹配抽取比较困难,于是用了python自带的SGMLParser,但是感觉不是很好用,不知道python有没有可以处理dom文档的好用的模块,寻找中...

上代码吧:

# -*- coding: UTF-8 -*-

import urllib2
from sgmllib import SGMLParser

#继承自SGMLParser,用于抽取新闻热搜词的类
class HotExtract(SGMLParser):
    
    '''
    20120814
         经分析,百度新闻热搜词的dom结构是下边这个样子的
    <a href="http://news.baidu.com/ns?cl=3&ct=9&rn=20&sp=hotquery&word=%C1%F5%CF%E8%20%BB%D8%B9%FA" target="_blank" mon="ct=1&a=30">刘翔回国</a>
         于是按<a>标签抽取,属性mon的值等于“ct=1&a=30”时判定为新闻热搜词标签
    '''
    def __init__(self):
        SGMLParser.__init__(self)
        self.is_a = ""
        self.hot = []
        
    def start_a(self, attrs):
        if len(attrs) == 0:
            pass
        else:
            for (variable, value) in attrs:
                if variable == "mon" and value == "ct=1&a=30":
                    self.is_a = 1
                    break
                
    def end_a(self):
        self.is_a = ""
        
    def handle_data(self, text):
        if self.is_a == 1:
            self.hot.append(text) 

#抓取html内容
def getHtml(url):
    html = urllib2.urlopen(url).read()
    return html

#抽取特定html标签中的内容(此处为抽取属性mon等于“ct=1&a=30”的a标签的text),重写HotExtract类可抽取其它内容
def extract_hot(html):
    hotExtract = HotExtract()
    hotExtract.feed(html)
    return hotExtract.hot

html = getHtml("http://news.baidu.com/")
hot_list = extract_hot(html)
for hot in hot_list:
    print hot
输出:
刘翔回国
打假传闻 歇业
保钓船 日本
深圳 城管外包
公务员砍人 戳伤
新24孝
安徽艳照门 双开
巩立姣补获铜牌
富二代 宝马肇事
分众 私有化
玉米 虫灾
摩托罗拉裁员
牛初乳禁令
赵普重现央视
高山回国自首
李娜 亚军
李婷去世
叙利亚总统特使访华
石家庄景观灯漏电
张成泽访华
3
3
分享到:
评论
3 楼 snowolf 2012-08-15  
sdu_wizard 写道
snowolf 写道
Python代码也太简洁了。。。。

要不是那个自定义的用于抽取的类,也就十几行代码。

用java得n多行,api底层封装的不够。。。。
2 楼 sdu_wizard 2012-08-15  
snowolf 写道
Python代码也太简洁了。。。。

要不是那个自定义的用于抽取的类,也就十几行代码。
1 楼 snowolf 2012-08-15  
Python代码也太简洁了。。。。

相关推荐

Global site tag (gtag.js) - Google Analytics