本文主要介绍将curl语法格式的命令改写为对应的python命令,实现同样的功能。主要有两种方法,第一种手动的方式,要求你对curl和python都比较熟悉,采用手动的方式改写;第二种方法借助于现成的工具,已经有在线工具网站提供对应的服务。以百度站长的普通收录服务https://ziyuan.baidu.com/linksubmit/index的示例curl推送代码为例,该curl推送代码将网站的链接主动推送到百度搜索引擎,加快收录, 当前不提供python格式的示例,所以要求开发者自行将curl推送示例改写为python格式。curl示例命令:

curl -H ‘Content-Type:text/plain’ –data-binary @urls.txt “http://data.zz.baidu.com/urls?site=https://www.example.cn&token=example

其中的urls.txt是本地创建的,并包含要推送的所有网页的链接url;

第一种手动改写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def push_to_baidu():
  file = "D:/example/urls.txt"
  headers = {
    'Content-Type': 'text/plain'
  }

  post_data = read_file(file)
  url = "http://data.zz.baidu.com/urls?site=www.book2you.net&token=pWJSVCQXgpRWvZbn"
  response = requests.post(url, headers=headers, data=post\_data)

def read_file(file):
  with open(file, encoding='UTF-8') as f:
    read_all = f.read()
    f.close()
  return read_all

经测试,上述代码运行后的response返回success.

第二种采用工具的方式:

使用Chrome登陆下面的网站:https://curl.trillworks.com/,在”language”一栏中选择”python”,如图1所示:

图1 工具网站的界面

然后将curl示例代码输入到左侧的”curl command”窗口,然后右侧的”Python Requests”就会自动出现对应的python格式代码,具体如图2所示:

图2 自动产生代码

自动产生的完整代码如下:

1
2
3
4
5
6
7
8
9
10
import requests
headers = {
'Content-Type': 'text/plain',
}
params = (
('site', '[https://www.example.cn](https://www.example.cn/)'),
('token', 'example'),
)
data = open('urls.txt', 'rb').read()
response = requests.post('http://data.zz.baidu.com/urls', headers=headers, params=params, data=data)

上述代码中的urls.txt的路径还需要根据自己的具体情况修改,经测试,上述代码正常可用.