首页 > 编程知识 正文

Python main函数,获取shell脚本参数

时间:2023-05-05 06:22:55 阅读:24461 作者:962

另一方面,介绍urllib.request.urlopen ()函数以实现对目标url的访问。

函数的原型如下。 urllib.request.urlopen(URL,data=None,[timeout,]*,cafile=None,capath=None,cadefault=False,ca file )

必须在url:中打开的网址

data :开机自检提交的数据

time out :设置网站的访问超时时间

直接在urllib.request模块的urlopen ()中检索页面。 page的数据格式为bytes型,需要用decode ) )进行解码并转换为str型。

2 .函数参数介绍

1. url参数:目标资源在网络上的位置。 它可以是表示URL的字符串。 例如,http://www.pythontab.com/; 它可以是urllib.request对象,有关详细信息,请跳

2. data参数: data用于指定服务器请求中的其他参数信息(例如在线翻译、在线解答等提交内容),data默认为None,在这种情况下以GET方式发送请求用户提交data参数时,更改为开机自检方式并发送请求。

3. timeout :设置站点访问超时时间

4. CAfile、capath、cadefault参数:实现可信ca证书的HTTP请求。 (基本上不怎么使用)

5. context参数:实现SSL加密传输。 (基本上不怎么使用)

三.详细了解返回处理方法urlopen返回对象提供方法:

read ()、readline、readlines、fileno )、close ) :使用HTTPResponse类型的数据

info ()返回http消息对象,并表示远程服务器返回的标头信息

返回getcode(:http状态代码。 对于http请求,200个请求已成功完成; 404未找到网站

geturl () :返回请求的url

四.版本差异、注意事项python2和python3的urlrequest导入方法不同。

python2是这样的。 import urllib2

另一方面,在python3中将urllib分开,分为urlrequest和urlerror。 这里只需要导入urlrequest即可。 from urllib.requestimporturlopen

5 .示例以下程序实现了urlopen ()函数的大多数功能,特别是data参数: 自定义数据、转换数据格式、数据编码encode ()和解码decode ) )。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

#编码=utf-8

#Python3.x

''''

使用有道翻译的在线翻译

''''

importurllib.request

importurllib.parse

导入JSON

欧盟信任(words ) :

#目标网址

targeturl=' http://fanyi.Youdao.com/translate? smart result=dictsmartresult=rulesmartresult=ugcsessionfrom=null '

#用户自定义表单,words表示用户翻译的内容。 此处使用的是dict类型,但也可以使用元组列表。

data={}

data['type']='AUTO '

data['i']=words

data['doctype']='json '

data [ ' XML版本' ]=' 1.8 '

data['keyfrom']='fanyi.web '

data['ue']='UTF-8 '

data [ ' action ' ]=' fy _ by _ click button '

data['typoResult']='true '

#将自定义data转换为标准格式

data=urllib.parse.urlencode (data ).encode (utf-8 ) ) ) ) ) ) )。

#发送用户请求

html=urllib.request.urlopen (targeturl,data ) ) ) ) ) ) ) )。

#读取内容并解码

rst=html.read ().decode () (utf-8 ) ) ) ) ) ) ) )。

rst_dict=json.loads(rst )

return rst _ dict [ ' translate result ' ] [0] [0] [ ' TGT ' ]

if__name__=='__main__':

输入print ()字符q时结束) ) )。

whileTrue:

words=input ('请输入要查询的单词或语句:n '。

ifwords=='q':

布雷克

结果=信任(words )

print ('翻译结果: %s'%result ) ) )。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。