Python网络数据采集4:使用API

   一般情况下,程序员可以用HTPP协议向API发起请求以获取某种信息,API会用XML或JSON格式返回服务器响应的信息。

   通常不会把使用API看成网络数据采集,但是实际上两者使用的许多技术(都是发送HTTP请求)和产生的结果(都是获取信息)差不多;两者经常是相铺相成的关系。

   如把维基百科编辑历史(里面有编辑者IP地址)和一个IP地址解析的API组合起来,以获取维基百科词条编辑者的地理位置。

4.1  API概述

     http://freegeoip.net/json/50.78.253.58

     Google API

4.2 API通用规则

    API用一套非常标准的规则生成数据,而且生成的数据也是按照非常标准的方式组织的。

    四种方式:GET, POST, PUT, DELETE

    验证:要求客户验证

4.3 服务器响应

   大多数反馈的数据格式是XML和JSON

    过去,服务器端用PHP和.NET这些程序作为API的接收端。现在,服务器端也会用一些JavaScript框架作为API的发送和接收端,像Angular或Backbone等。

   API调用:

4.4 Echo Nest

     The Echo Nest 音乐数据网站 https://developer.echonest.com/account/register

4.5 Twitter API

     https://apps.twitter.com/app/new

     pip install twitter

from twitter import Twitter
t = Twitter(auth=OAuth(<Access Token>,<Access Token Secret>,<Consumer Key>,<Consumer Secret>))
pythonTweets = t.search.tweets(q = "#python")
print(pythonTweets)
     发一篇推文

4.6 Google API

    无论你想处理哪种信息,包括语言翻译、地理位置、日历,甚至基因数据,Google 都提供了API。Google 还为它的一些知名应用提供 API,比如 Gmail、YouTube 和 Blogger 等。

4.7 解析JSON数据

import json
from urllib.request import urlopen
def getCountry(ipAddress):
	response = urlopen("http://freegeoip.net/json/"+ipAddress).read().decode('utf-8')
	responseJson = json.loads(response)
	return responseJson.get("country_code")
print(getCountry("50.78.253.58"))

4.8 回到主题

    把多个数据源组合成新的形式,或者把API作为一种工具,从全新的视角对采集到的数据进行解释。

    首先做一个采集维基百科的基本程序,寻找编辑历史页面,然后把编辑历史里面的IP地址找出来

# -*- coding: utf-8 -*-
from urllib.request import urlopen
from bs4 import BeautifulSoup
import datetime
import random
import re
import json

random.seed(datetime.datetime.now())
# https://en.wikipedia.org/wiki/Python_(programming_language)
def getLinks(articleUrl):
	html = urlopen("http://en.wikipedia.org"+articleUrl)
	bsObj = BeautifulSoup(html)
	return bsObj.find("div",{"id":"bodyContent"}).findAll("a", href=re.compile("^(/wiki/)((?!:).)*$"))

def getHistoryIPs(pageUrl):
	# 编辑历史页面URL链接格式是:
	# https://en.wikipedia.org/w/index.php?title=Python_(programming_language)&action=history
	pageUrl = pageUrl.replace("/wiki/", "")
	historyUrl = "https://en.wikipedia.org/w/index.php?title="+pageUrl+"&action=history"
	print("history url is: "+historyUrl)
	html = urlopen(historyUrl)
	bsObj = BeautifulSoup(html)
	# 找出class属性是"mw-anonuserlink"的链接
	# 它们用IP地址代替用户名
	ipAddresses = bsObj.findAll("a", {"class":"mw-anonuserlink"})
	addressList = set()
	for ipAddress in ipAddresses:
		addressList.add(ipAddress.get_text())
	return addressList

links = getLinks("/wiki/Python_(programming_language)")

def getCountry(ipAddress):
	try:
		response = urlopen("http://freegeoip.net/json/"+ipAddress).read().decode('utf-8')
	except HTTPError:
		return None
	responseJson = json.loads(response)
	return responseJson.get("country_code")

while (len(links) > 0):
	for link in links:
		print("-------------------")
		historyIPs = getHistoryIPs(link.attrs["href"])
		for historyIP in historyIPs:
			#print(historyIP)
			country = getCountry(historyIP)
			if country is not None:
				print(historyIP+" is from "+country)
	newLink = links[random.randint(0, len(links)-1)].attrs["href"]
	links = getLinks(newLink)

4.9 再说一点API

Leonard Richardson、Mike Amundsen 和 Sam Ruby 的 RESTful Web APIs (http://shop.oreilly.com/product/0636920028468.do)为网络 API 的用法提供了非常全面的理论与实践指导。另外,Mike Amundsen 的精彩视频教学课程 Designing APIs for the Web(http://shop.oreilly.com/product/110000125.do),也可以教你创建自己的 API。如果你想把自己采集的数据用一种便捷的方式分享出来,他的视频非常有用

    



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值