能够从网页上面获取相关的响应内容是 Python 爬虫的第一步,而 urllib2 的 python 库正是爬取网页内容的重要的库。我们使用 urllib2 完成对金山词霸的每日金句的获取,并且对获取到的内容进行提取操作,去除脏数据保留有用数据。
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
import urllib2
import json
def getSentence():
# 金山词霸地址
address = "http://open.iciba.com/dsapi";
# 模拟用户请求头
headers = {
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_3 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) CriOS/66.0.3359.122 Mobile/15E216 Safari/604.1"
};
# 发送请求
request = urllib2.Request(address,headers=headers);
# 接收响应
response = urllib2.urlopen(request);
# 提取响应内容
result = response.read();
# 对结果进行 utf-8 解码
result = result.decode('utf-8');
# json 格式转换
result_json = json.loads(result);
# 提取内容
content = result_json['content']
# 提取翻译后的内容
translation = result_json['translation']
# 提取 note
note = result_json['note']
# 返回字典
return content, note, translation
if __name__ == '__main__':
resu = getSentence();
print resu[0]
print resu[1]
print resu[2]
转载请注明:XAMPP中文组官网 » Python入门实战项目之获取金山词霸每日金句