python基础 刻意练习 小甲鱼教程之爬虫P053- by littlecircle327

053-054
Python如何访问互联网

url的一般格式为:
Protocol://hostname[:port]/path/[;parameters][?query]#fragment

URL由三部分组成:
—第一部分是协议:http,https,ftp,file,ed2k…
—第二部分是存放资源的服务器的域名系统或IP地址(有时候要包含端口号,各种传输协议都有默认的端口号,如http的默认端口为80)。
—第三部分是资源的具体地址。(就是杠后面那些)

现在urllib块把urllib2都合并了
要爬虫一般用urllib.request模块
常用的有.urlopen等函数


eg 01 访问测试

import urllib.request
response = urllib.request.urlopen("http://www.fishc.com")
html = response.read()
html = html.decode("utf-8")
print(html)

eg 02 爬猫图

import urllib.request
response =urllib.request.urlopen('http://placekitten.com/g/400/600')

#http://photocdn.sohu.com/20160928/Img469362391.jpg就是图片的地址
#req=urllib.request.Request("http://placekitten.com/g/500/600")
#response = urllib.request.urlopen(req)都可以的

cat_img = response.read()

with open('cat_400_600.jpg', 'wb') as f:
    f.write(cat_img)
# 接下来的操作

#response.geturl()
#    'http://placekitten.com/g/500/600'

#response.info()
#    <http.client.HTTPMessageobject at 0x032903B0>  #得到的是一个对象  

#print(response.info()) #能打印一堆东西

#response.getcode()
# 200 是正常的

eg 03 爬有道词典

右键fanyi.youdao.com,点审查元素/检查(N)
然后点Network,点左面的翻译,可以看到新生成的一堆,虽然找不到教程中说的POST 和GET的这2个Method类,但是知道后面这几个是新增的,然后一个个点,点到这个translate_o,发现Preview有我输入的英文,说明对了,点Headers,看到方法是post,一般Post和get一个是发送一个是接收。

再往下看,有这些东西
Request URL: http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule
Request Method: POST
Status Code: 200 OK
Remote Address: 61.135.217.21:80 #是端口地址
Referrer Policy: no-referrer-when-downgrade

下面:
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
是来get你是什么,是不是机器人。

Form data 你提交的主要内容

重新看.request函数,data=None就是get方法,有data就是post方法

然后套用模板一点点爬。
然后发现输出是errorcode50,说明有问题,百度了一下,有好2种解决方法。

方法1
去掉_o,可以运行,我感觉这说明_o可能是新版本,之前是老版本。

import urllib.request
import urllib.parse
import json
content ='I love him'
#content =input("输入需要翻译的内容:")
url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
#url='http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

data = {
   }
data['i'] = content
data['from'] = 'AUTO'
data['to'] = 'AUTO'
data['smartresult'] = 'dict'
data['client'] =  'fanyideskweb'
data
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值