码迷,mamicode.com
首页 > 其他好文 > 详细

拓展 封装

时间:2018-08-13 23:55:28      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:headers   urllib   html_   app   www.   safari   pen   web   main   

from urllib import request, parse
from urllib.error import HTTPError, URLError

# a. get(url, headers=None)
def get(url, headers=None):
return urlrequests(url, headers=headers)

# b. post(url, from, headers=None)
def post(url,form, headers=None):
return urlrequests(url, form, headers=headers)

def urlrequests(url, form=None, headers=None):
user_agent = ‘Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36‘
# 如果用户需要自行传入session,则会覆盖之前的session
if headers == None:
headers = {
‘User-Agent‘:user_agent
}
html_bytes = b‘‘
try:
if form:
# POST
# 2.1 转换成str
form_str = parse.urlencode(form)
# 2.2 转换成bytes
form_bytes = form_str.encode(‘utf-8‘)
req = request.Request(url, data= form_bytes, headers=headers)
else:
# GET
req = request.Request(url, headers=headers)
response = request.urlopen(req)
html_bytes = response.read()

except HTTPError as e:
print(e)
except URLError as e:
print(e)
return html_bytes

if __name__ == ‘__main__‘:
# url = ‘http://www.baidu.com‘
# html_byte = get(url)
# print(html_byte)


url = ‘http://fanyi.baidu.com/sug‘
form = {
‘kw‘:‘黄色‘
}
html_bytes= post(url,form =form)
print(html_bytes)

拓展 封装

标签:headers   urllib   html_   app   www.   safari   pen   web   main   

原文地址:https://www.cnblogs.com/huangming17/p/9471530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!