python:爬虫1——实战(下载一张图片、用Python模拟浏览器,通过在线的有道词典来对文本翻译)...

一、下载一只猫

import urllib.request

response = urllib.request.urlopen("http://cdn.duitang.com/uploads/item/201111/24/20111124222137_wHYwc.jpg")
cat_img = response.read()

with open('cat_0.jpeg', 'wb') as f:
    f.write(cat_img)

 

urlopen()中的url可以是string,也可以是request object,因此可以是:

import urllib.request

req = urllib.request.Request("http://cdn.duitang.com/uploads/item/201111/24/20111124222137_wHYwc.jpg")
response = urllib.request.urlopen(req)
cat_img = response.read()

with open('cat_0.jpeg', 'wb') as f:
    f.write(cat_img)

 

response.geturl()得到url地址

response.info()得到HTTPMessage对象,可以通过print()得到head信息

response.getcode()得到服务器的状态码200(正常响应)

二、利用有道词典翻译文本

<审查元素>network——preview,找到需要的path

然后切到headers——关注general、request headers(客户端发送请求的headers,服务端可以在此判断是否人为访问,User-Agent)python url/3.4、From Data、

urlopen()中data为None以get提交,有参数用post方式提交,data参数必须是一个标准格式application/x-www-form-urlencoded,可以用urllib.parse.urlencode()来将字符串转化为这个格式

import urllib.request
import urllib.parse
import json

url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule&sessionFrom=http://fanyi.youdao.com/'

data = {
'i':'china',
'from':'AUTO',
'to':'AUTO',
'smartresult':'dict',
'sign':'cf928c9af5dc3731276ad09db002e052',
'client':'fanyideskweb',
'salt':'1494249290636',
'doctype':'json',
'version':'2.1',
'keyfrom':'fanyi.web',
'action':'FY_BY_CLICKBUTTON',
'typoResult':'true'
}

data = urllib.parse.urlencode(data).encode('utf8')
response = urllib.request.urlopen(url, data)
html = response.read().decode('utf-8')

print(html)    #发现是json格式

target = json.loads(html)

print(target)   #打印还原的json

 但是当客户端码是python,并且当一个ip访问太多后,服务器会拉黑ip!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值