跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

这段php或是ruby的post代码如何转换翻译成Python?

这是一个百度站长平台的推送事例: post事例: POST /urls?site=www.nantongzt.com&token=xxxxxx HTTP/1.1 User-Agent: curl/7.12.1 Host: data.zz.baidu.com Content-Type: text/plain Content-Length: 83 http://www.example.com/1.html http://www.example.com/2.html 立即学习 “ PHP免费学习笔记(深入) ”; php 的推送事例:
$urls = array( 'http://www.example.com/1.html', 'http://www.example.com/2.html', ); $api = 'http://data.zz.baidu.com/urls?site=www.nantongzt.com&token=xxxxxx'; $ch = curl_init(); $options = array( CURLOPT_URL => $api, CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => implode("\n", $urls), CURLOPT_HTTPHEADER => array('Content-Type: text/plain'), ); curl_setopt_array($ch, $options); $result = curl_exec($ch); echo $result;
ruby的事例
require 'net/http' urls = ['http://www.example.com/1.html', 'http://www.example.com/2.html'] uri = URI.parse('http://data.zz.baidu.com/urls?site=www.nantongzt.com&token=xxxxxx') req = Net::HTTP::Post.new(uri.request_uri) req.body = urls.join("\n") req.content_type = 'text/plain' res = Net::HTTP.start(uri.hostname, uri.port) { |http| http.request(req) } puts res.body
其实应该很简单,就是如何用 python post提交数据. 但是看php和ruby的代码又不是很像~ 希望有高人指点一下,个人比较菜~希望有翻译得详细一点,谢谢了! 回复内容: 这是一个百度站长平台的推送事例: post事例: POST /urls?site=www.nantongzt.com&token=xxxxxx HTTP/1.1 User-Agent: curl/7.12.1 Host: data.zz.baidu.com Content-Type: text/plain Content-Length: 83 http://www.example.com/1.html http://www.example.com/2.html 立即学习 “ PHP免费学习笔记(深入) ”; php的推送事例:
$urls = array( 'http://www.example.com/1.html', 'http://www.example.com/2.html', ); $api = 'http://data.zz.baidu.com/urls?site=www.nantongzt.com&token=xxxxxx'; $ch = curl_init(); $options = array( CURLOPT_URL => $api, CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => implode("\n", $urls), CURLOPT_HTTPHEADER => array('Content-Type: text/plain'), ); curl_setopt_array($ch, $options); $result = curl_exec($ch); echo $result;
ruby的事例
require 'net/http' urls = ['http://www.example.com/1.html', 'http://www.example.com/2.html'] uri = URI.parse('http://data.zz.baidu.com/urls?site=www.nantongzt.com&token=xxxxxx') req = Net::HTTP::Post.new(uri.request_uri) req.body = urls.join("\n") req.content_type = 'text/plain' res = Net::HTTP.start(uri.hostname, uri.port) { |http| http.request(req) } puts res.body
其实应该很简单,就是如何用python post提交数据. 但是看php和ruby的代码又不是很像~ 希望有高人指点一下,个人比较菜~希望有翻译得详细一点,谢谢了!
#coding=utf-8 import requests urls = [ 'http://www.example.com/1.html', 'http://www.example.com/2.html' ] api = 'http://data.zz.baidu.com/urls?site=www.nantongzt.com&token=xxxxxx' data = '\n'.join(urls) headers = {'Content-Type': 'text/plain'} r = requests.post(api, data=data, headers=headers) print r.text

相关文章