yuanqiao 发表于 2017-5-1 15:26:23

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孝

安徽艳照门 双开

巩立姣补获铜牌

富二代 宝马肇事

分众 私有化

玉米 虫灾

摩托罗拉裁员

牛初乳禁令

赵普重现央视

高山回国自首

李娜 亚军

李婷去世

叙利亚总统特使访华

石家庄景观灯漏电

张成泽访华
页: [1]
查看完整版本: Python抓取百度热搜词