from urllib import request,parse
from urllib.error import HTTPError,URLError
import json
# get请求
def get(url,headers = None):
return urlrequests(url,headers=headers)
# post请求
def post(url,form=None,headers=None):
# 解析json
res_dict = json.loads(urlrequests(url,form,headers=headers).decode('utf-8'))
return res_dict
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'
if headers == None:
headers = {
'User-Agent':user_agent
}
html = b''
try:
if form:
# 转换成str
form_str = parse.urlencode(form)
#转换成字节
form_mm = form_str.encode('utf-8')
# 发送post请求
response = request.Request(url,data = form_mm,headers=headers)
else:
# 发送请求
response = request.Request(url,headers=headers)
# 返回请求的结果
result = request.urlopen(response)
# 返回网页代码
html = result.read()
except HTTPError as f:
print(f)
except URLError as f:
print(f)
return html
# 调试
if __name__ == '__main__':
url = 'http://fanyi.baidu.com/sug'
form = {
'kw': '呵呵'
}
html_bytes = post (url, form=form)
print(html_bytes)
# url = 'http://www.baidu.com'
# res = urlrequests(url)
# print(res.decode('utf-8'))
python爬虫封装1
最新推荐文章于 2023-03-31 12:36:12 发布