【python】web网络请求学习

和nodejs相比感觉怪怪的,最简单的get请求

python 3

import urllib.request
from urllib.error import HTTPError
import json

req = urllib.request.Request(url=r"http://api.ibeeger.com",headers={'User-Agent':' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0'})
try:
    handler = urllib.request.urlopen(req)
    content = handler.read()
    content = json.loads(content)
    print(content['browser'])
except HTTPError as e:
    content = e.read()
    print(content)

nodejs

const http = require('http')
http.get({
	hostname: 'api.ibeeger.com',
	headers: {
		'user-agent': 'Mozilla/5.0'
	}
}, function(res) {
	console.log(res.statusCode)
	let body = '';
	res.on('data', function(bf) {
		body += bf
	})
	res.on('end', function() {
		console.log(JSON.parse(body))
	})
})

后面再对比其他方面吧

发布了77 篇原创文章 · 获赞 5 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/uk_51/article/details/89061304