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!

原文地址:https://www.cnblogs.com/daduryi/p/6829969.html