python如何访问互联网?

- URL的一般格式为(带方括号[]的为可选项):
protocol :// hostname[:port] / path / [;parameters][?query]#fragment
- URL由三部分组成:
第一部分是协议:http,https,ftp,file,ed2k…
http协议
第二部分是存放资源的服务器的域名系统或IP地址(有时候要包含端口号,各种传输协议都有默认的端口号,如http的默认端口为80)。
第三部分是资源的具体地址,如目录或文件名等。
尝试访问
源码:
import urllib.request#导包
reponse=urllib.request.urlopen("http://www.baidu.com")
html=reponse.read()#读取内容
print(html)#打印内容
html=hyml.decode("utf-8")#编码转换可转换为网页的源代码

直接实战
访问placekitten.com获取图片
目标文件

新建python文档-----download_cat.py
import urllib.request
response = urllib.request.urlopen('http://placekitten.com/g/600/700')# 返回文件对象response
cat_imag = response.read()
with open('cat_600_700.jpg','wb') as f:
f.write(cat_imag)
结果演示

response.geturl()获取url地址

response.info()获取HTTPmessage对象

打印结果

response.getcode()HTTP响应状态

用有道词典翻译文本
目标:模拟浏览器进行翻译

创建translation.py
源码:
import json
import urllib.parse
import urllib.request
content = input("请输入需要翻译的内容:")
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
data = {}
data['type'] = 'AUTO'
data['i'] = content
data['doctype'] = 'json'
data['xmlVersion'] = '1.6'
data['keyfrom'] = 'fanyi.web'
data['ue'] = 'UTF-8'
data['typoResult'] = 'true'
data=urllib.parse.urlencode(data).encode('utf-8')
response=urllib.request.urlopen(url,data)
html=response.read().decode('utf-8')
target=json.loads(html)
print("翻译结果:%s"%(target['translateResult'][0][0]['tgt']))
结果没有想到😭😭😭😭😭😭

有兴趣的同学可以参考一下这篇文章https://blog.csdn.net/weixin_43750377/article/details/107222836
本文介绍了Python通过urllib库访问互联网的基本方法,包括获取网页内容、下载图片以及使用有道词典API进行文本翻译。示例代码详细展示了如何使用urllib.request模块打开URL,读取响应内容,以及进行HTTP请求。此外,还提供了访问placekitten.com获取猫咪图片并保存到本地的示例,以及模拟浏览器进行翻译的实现。
425

被折叠的 条评论
为什么被折叠?



