python爬虫基础封装函数
2018-08-13 20:10
645 查看
[code]# 导入包,模块 from urllib import request, parse from urllib.error import HTTPError, URLError #保存cookie from http import cookiejar #对于有登录是 所将用户记录下来 , class session(object): def __init__(self): cookie_object = cookiejar.CookieJar() #handler 对应着一个操作 handler = request.HTTPCookueProcessor(cookie_object) #调用handler内部的一个函数,存储到cookie object self.opener = request.build_opener(handler) # get请求时 def get(self, url, headers=None): return get(url, headers, self.opener) #post请求时 def post(self, url, from, headers=None): return post(url, form, headers, self.opener) # 定义函数 # get方法 def get(url, headers=None): return urlrequests(url, headers=headers) # post方法 def post(url, form, headers=None): return urlrequests(url,form, headers = headers) # 进行封装函数 # 1.传入url # 2.user_agent # 3.headers # 4.定义Request # 5.urlopen # 6.返回byte数组 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_bytes = b'' try: if form: # POST 转换成str from_str = parse.urlencode( form) # 转换成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://fanyi.baidu.com/sug' # form = { # 'kw': '翻译的内容' # } # #post访问 # html_bytes = post(url, form=form) # print(html_bytes) url = 'http://www.baidu.com' # get访问 html_byte = get(url) print(html_byte)阅读更多
相关文章推荐
- Python基础--第6章 函数操作——功能化程序片段的封装
- 简单爬虫函数的封装(Python)
- 2018年最新Python3.6网络爬虫实战案例基础+实战+框架+分布式高清视频教程(完整版)
- python基础学习之函数(2)-内嵌函数和闭包
- python基础===通过菲波那契数列,理解函数
- Python爬虫_基础
- python程序设计基础4:python函数设计和使用
- 零基础自学用Python 3开发网络爬虫(二): 用到的数据结构简介以及爬虫Ver1.0 alpha
- Python零基础入门十九之爬虫基础知识
- 自学Python四 爬虫基础知识储备
- python基础笔记2-字符串处理函数
- Python新手学习基础之函数-概念与定义
- python基础07 函数
- Python 函数封装
- Python基础-函数
- Python基础(函数,函数的定义,函数的调用,函数的参数,递归函数)
- javascript 面向对象基础(一)对象组成及函数封装
- 【Python自学】08. 函数基础(上)
- python基础——函数的参数