Request对象的作用是与客户端交互,收集客户端的Form、Cookies、超链接,或者收集服务器端的环境变量。request对象是从客户端向服务器发出请求,包括用户提交的信息以及客户端的一些信息。客户端可通过HTML表单或在网页地址后面提供参数的方法提交数据,然后服务器通过request对象的相关方法来获取这些数据。request的各种方法主要用来处理客户端浏览器提交的请求中的各项参数和选项。
get 用于向服务器获取数据 post用于传递数据``
url.parse :定义了url的标准接口,实现url的各种抽取
parse模块的使用:url的解析,合并,编码,解码
使用时需导入
from urllib import parse
import urllib.request
import urllib.parse
import json
content = input("请输入要翻译的内容")
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
date = {}
date['i']: '我学python'
date['from']: 'AUTO'
date['to']: 'AUTO'
date['smartresult']: 'dict'
date['client']: 'fanyideskweb'
date['salt']: '15825481693233'
date['sign']: '1badaf889f16c8fda0a2a0c05ec3d68c'
date['ts']: '1582548169323'
date['bv']: '901200199a98c590144a961dac532964'
date['doctype']: 'json'
date['version']: '2.1'
date['keyfrom']: 'fanyi.web'
date['action']: 'FY_BY_REALTlME'
date = urllib.parse.urlencode(date).encode('utf-8')
response = urllib.request.urlopen(url,date)
html = response.read().decode('utf-8')
target = json.loads(html)
print("翻译结果是:%s"%(target['translateRequest'][0][0]['tgt']))
以上是有道词典翻译网页的爬取
为了防止被认为是脚本访问 可以在对象生成之前添加head 和User-Agent
head{}
head['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'
或者在对象生成之后用add_head(key,val)和User-Agent
add_head('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'
)
加入time模块后能更好的实现
import urllib.request
import urllib.parse
import json
while True:
content = input("请输入要翻译的内容:")
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
date = {}
date['i']: '我学python'
date['from']: 'AUTO'
date['to']: 'AUTO'
date['smartresult']: 'dict'
date['client']: 'fanyideskweb'
date['salt']: '15825481693233'
date['sign']: '1badaf889f16c8fda0a2a0c05ec3d68c'
date['ts']: '1582548169323'
date['bv']: '901200199a98c590144a961dac532964'
date['doctype']: 'json'
date['version']: '2.1'
date['keyfrom']: 'fanyi.web'
date['action']: 'FY_BY_REALTlME'
date = urllib.parse.urlencode(date).encode('utf-8')
response = urllib.request.urlopen(url,date)
html = response.read().decode('utf-8')
target = json.loads(html)
print("翻译结果是:%s"%(target['translateRequest'][0][0]['tgt']))
print(target)
time.sleep(5)#每次休息五秒种
也可以使用代理(最好)
1.参数是一个字典{‘类型’,‘代理IP:端口号’}
porxy_support = urllib.request.ProxyHandler({})
2.定制,创建一个opener
opener = urllib.request.build_opener(proxy_support)
3.a 安装opener
urllib.request.install_opener(opener)
3.b 调用opener
opener.open(url)
import urllib.request
url = 'http://www.whatismyip.com.tw'
porxy_support = urllib.request.ProxyHandler({'http':'119.6.144.73.81'})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
response = urllib.request.urlopen(url)
html = response.read().decode('utf-8')
print(html)