爬虫基础模块

Python标准库中提供了:urllib、urllib2、httplib等模块以供Http请求,但是,它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。

Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网络请求时,变得美好了许多,使用Requests可以轻而易举的完成浏览器可有的任何操作。

# 1、无参数实例

import requests

ret = requests.get(‘https://github.com/timeline.json‘)

print ret.url
print ret.text

# 2、有参数实例

import requests

payload = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘}
ret = requests.get("http://httpbin.org/get", params=payload)
  #get传值
print ret.url
print ret.text

requests的get请求

import requests

payload = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘}
ret = requests.post("http://httpbin.org/post", data=payload)

print ret.text

# 2、发送请求头和数据实例

import requests
import json

url = ‘https://api.github.com/some/endpoint‘
payload = {‘some‘: ‘data‘}
headers = {‘content-type‘: ‘application/json‘}

ret = requests.post(url, data=json.dumps(payload), headers=headers)

print ret.text
print ret.cookies

requests的post请求

requests.get(url, params=None, **kwargs)
requests.post(url, data=None, json=None, **kwargs)
requests.put(url, data=None, **kwargs)
requests.head(url, **kwargs)
requests.delete(url, **kwargs)
requests.patch(url, data=None, **kwargs)
requests.options(url, **kwargs)

# 以上方法均是在此方法的基础上构建
requests.request(method, url, **kwargs)
#所以使用方法基本一致

requests其他操作

def param_method_url():
    # requests.request(method=‘get‘, url=‘http://127.0.0.1:8000/test/‘)
    # requests.request(method=‘post‘, url=‘http://127.0.0.1:8000/test/‘)
    pass

def param_param():
    # - 可以是字典
    # - 可以是字符串
    # - 可以是字节(ascii编码以内)

    # requests.request(method=‘get‘,
    # url=‘http://127.0.0.1:8000/test/‘,
    # params={‘k1‘: ‘v1‘, ‘k2‘: ‘水电费‘})

    # requests.request(method=‘get‘,
    # url=‘http://127.0.0.1:8000/test/‘,
    # params="k1=v1&k2=水电费&k3=v3&k3=vv3")

    # requests.request(method=‘get‘,
    # url=‘http://127.0.0.1:8000/test/‘,
    # params=bytes("k1=v1&k2=k2&k3=v3&k3=vv3", encoding=‘utf8‘))

    # 错误
    # requests.request(method=‘get‘,
    # url=‘http://127.0.0.1:8000/test/‘,
    # params=bytes("k1=v1&k2=水电费&k3=v3&k3=vv3", encoding=‘utf8‘))
    pass

def param_data():
    # 可以是字典
    # 可以是字符串
    # 可以是字节
    # 可以是文件对象

    # requests.request(method=‘POST‘,
    # url=‘http://127.0.0.1:8000/test/‘,
    # data={‘k1‘: ‘v1‘, ‘k2‘: ‘水电费‘})

    # requests.request(method=‘POST‘,
    # url=‘http://127.0.0.1:8000/test/‘,
    # data="k1=v1; k2=v2; k3=v3; k3=v4"
    # )

    # requests.request(method=‘POST‘,
    # url=‘http://127.0.0.1:8000/test/‘,
    # data="k1=v1;k2=v2;k3=v3;k3=v4",
    # headers={‘Content-Type‘: ‘application/x-www-form-urlencoded‘}
    # )

    # requests.request(method=‘POST‘,
    # url=‘http://127.0.0.1:8000/test/‘,
    # data=open(‘data_file.py‘, mode=‘r‘, encoding=‘utf-8‘), # 文件内容是:k1=v1;k2=v2;k3=v3;k3=v4
    # headers={‘Content-Type‘: ‘application/x-www-form-urlencoded‘}
    # )
    pass

def param_json():
    # 将json中对应的数据进行序列化成一个字符串,json.dumps(...)
    # 然后发送到服务器端的body中,并且Content-Type是 {‘Content-Type‘: ‘application/json‘}
    requests.request(method=‘POST‘,
                     url=‘http://127.0.0.1:8000/test/‘,
                     json={‘k1‘: ‘v1‘, ‘k2‘: ‘水电费‘})

def param_headers():
    # 发送请求头到服务器端
    requests.request(method=‘POST‘,
                     url=‘http://127.0.0.1:8000/test/‘,
                     json={‘k1‘: ‘v1‘, ‘k2‘: ‘水电费‘},
                     headers={‘Content-Type‘: ‘application/x-www-form-urlencoded‘}
                     )

def param_cookies():
    # 发送Cookie到服务器端
    requests.request(method=‘POST‘,
                     url=‘http://127.0.0.1:8000/test/‘,
                     data={‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘},
                     cookies={‘cook1‘: ‘value1‘},
                     )
    # 也可以使用CookieJar(字典形式就是在此基础上封装)
    from http.cookiejar import CookieJar
    from http.cookiejar import Cookie

    obj = CookieJar()
    obj.set_cookie(Cookie(version=0, name=‘c1‘, value=‘v1‘, port=None, domain=‘‘, path=‘/‘, secure=False, expires=None,
                          discard=True, comment=None, comment_url=None, rest={‘HttpOnly‘: None}, rfc2109=False,
                          port_specified=False, domain_specified=False, domain_initial_dot=False, path_specified=False)
                   )
    requests.request(method=‘POST‘,
                     url=‘http://127.0.0.1:8000/test/‘,
                     data={‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘},
                     cookies=obj)

def param_files():
    # 发送文件
    # file_dict = {
    # ‘f1‘: open(‘readme‘, ‘rb‘)
    # }
    # requests.request(method=‘POST‘,
    # url=‘http://127.0.0.1:8000/test/‘,
    # files=file_dict)

    # 发送文件,定制文件名
    # file_dict = {
    # ‘f1‘: (‘test.txt‘, open(‘readme‘, ‘rb‘))
    # }
    # requests.request(method=‘POST‘,
    # url=‘http://127.0.0.1:8000/test/‘,
    # files=file_dict)

    # 发送文件,定制文件名
    # file_dict = {
    # ‘f1‘: (‘test.txt‘, "hahsfaksfa9kasdjflaksdjf")
    # }
    # requests.request(method=‘POST‘,
    # url=‘http://127.0.0.1:8000/test/‘,
    # files=file_dict)

    # 发送文件,定制文件名
    # file_dict = {
    #     ‘f1‘: (‘test.txt‘, "hahsfaksfa9kasdjflaksdjf", ‘application/text‘, {‘k1‘: ‘0‘})
    # }
    # requests.request(method=‘POST‘,
    #                  url=‘http://127.0.0.1:8000/test/‘,
    #                  files=file_dict)

    pass

def param_auth():
    from requests.auth import HTTPBasicAuth, HTTPDigestAuth

    ret = requests.get(‘https://api.github.com/user‘, auth=HTTPBasicAuth(‘wupeiqi‘, ‘sdfasdfasdf‘))
    print(ret.text)

    # ret = requests.get(‘http://192.168.1.1‘,
    # auth=HTTPBasicAuth(‘admin‘, ‘admin‘))
    # ret.encoding = ‘gbk‘
    # print(ret.text)

    # ret = requests.get(‘http://httpbin.org/digest-auth/auth/user/pass‘, auth=HTTPDigestAuth(‘user‘, ‘pass‘))
    # print(ret)
    #

def param_timeout():
    # ret = requests.get(‘http://google.com/‘, timeout=1)
    # print(ret)

    # ret = requests.get(‘http://google.com/‘, timeout=(5, 1))
    # print(ret)
    pass

def param_allow_redirects():
    ret = requests.get(‘http://127.0.0.1:8000/test/‘, allow_redirects=False)
    print(ret.text)

def param_proxies():
    # proxies = {
    # "http": "61.172.249.96:80",
    # "https": "http://61.185.219.126:3128",
    # }

    # proxies = {‘http://10.20.1.128‘: ‘http://10.10.1.10:5323‘}

    # ret = requests.get("http://www.proxy360.cn/Proxy", proxies=proxies)
    # print(ret.headers)

    # from requests.auth import HTTPProxyAuth
    #
    # proxyDict = {
    # ‘http‘: ‘77.75.105.165‘,
    # ‘https‘: ‘77.75.105.165‘
    # }
    # auth = HTTPProxyAuth(‘username‘, ‘mypassword‘)
    #
    # r = requests.get("http://www.google.com", proxies=proxyDict, auth=auth)
    # print(r.text)

    pass

def param_stream():
    ret = requests.get(‘http://127.0.0.1:8000/test/‘, stream=True)
    print(ret.content)
    ret.close()

    # from contextlib import closing
    # with closing(requests.get(‘http://httpbin.org/get‘, stream=True)) as r:
    # # 在此处理响应。
    # for i in r.iter_content():
    # print(i)

def requests_session():
    import requests

    session = requests.Session()

    ### 1、首先登陆任何页面,获取cookie

    i1 = session.get(url="http://dig.chouti.com/help/service")

    ### 2、用户登陆,携带上一次的cookie,后台对cookie中的 gpsd 进行授权
    i2 = session.post(
        url="http://dig.chouti.com/login",
        data={
            ‘phone‘: "8615131255089",
            ‘password‘: "xxxxxx",
            ‘oneMonth‘: ""
        }
    )

    i3 = session.post(
        url="http://dig.chouti.com/link/vote?linksId=8589623",
    )
    print(i3.text)

示例

BeautifulSoup是一个模块,该模块用于接收一个HTML或XML字符串,然后将其进行格式化,之后遍可以使用他提供的方法进行快速查找指定元素,从而使得在HTML或XML中查找指定元素变得简单。

时间: 2024-08-24 06:33:23

爬虫基础模块的相关文章

node.js基础模块http、网页分析工具cherrio实现爬虫

node.js基础模块http.网页分析工具cherrio实现爬虫 一.前言      说是爬虫初探,其实并没有用到爬虫相关第三方类库,主要用了node.js基础模块http.网页分析工具cherrio. 使用http直接获取url路径对应网页资源,然后使用cherrio分析. 这里我主要学习过的案例自己敲了一遍,加深理解.在coding的过程中,我第一次把jq获取后的对象直接用forEach遍历,直接报错,是因为jq没有对应的这个方法,只有js数组可以调用. 二.知识点    ①:supera

python学习八十四天:爬虫基础

爬虫基础 爬虫相关概念简介 什么是爬虫 爬虫就是通过编写程序模拟浏览器上网,然后让其去互联网上抓取数据的过程. 哪些语言可以实现爬虫 1.php:可以实现爬虫.php被号称是全世界最优美的语言(当然是其自己号称的,就是王婆卖瓜的意思),但是php在实现爬虫中支持多线程和多进程方面做的不好. 2.java:可以实现爬虫.java可以非常好的处理和实现爬虫,是唯一可以与python并驾齐驱且是python的头号劲敌.但是java实现爬虫代码较为臃肿,重构成本较大. 3.c.c++:可以实现爬虫.但是

爬虫基础以及一个简单的实例

最近在看爬虫方面的知识,看到崔庆才所著的<Python3网络爬虫开发实战>一书讲的比较系统,果断入手学习.下面根据书中的内容,简单总结一下爬虫的基础知识,并且实际练习一下.详细内容请见:https://cuiqingcai.com/5465.html(作者已把书的前几章内容对外公开). 在写爬虫程序之前需要了解的一些知识: 爬虫基础:我们平时访问网页就是对服务器发送请求(Request),然后得到响应(Response)的一个过程.爬虫通过模仿浏览器,对网页进行自动访问.需要知道请求包含哪些内

爬虫基础之urllib库

categories: 爬虫 tags: urlopen urlretrieve urlencode parse_qs urlparse urlsplit urllib库 urllib库是Python中一个最基本的网络请求库.可以模拟浏览器的行为,向指定的服务器发送一个请求,并可以保存服务器返回的数据 urlopen函数 在Python3的urllib库中,所有和网络请求相关的方法,都被集到 urllib.request 模块下面了,先来看下urlopen的基本使用 from urllib im

转 Python爬虫入门二之爬虫基础了解

静觅 » Python爬虫入门二之爬虫基础了解 2.浏览网页的过程 在用户浏览网页的过程中,我们可能会看到许多好看的图片,比如 http://image.baidu.com/ ,我们会看到几张的图片以及百度搜索框,这个过程其实就是用户输入网址之后,经过DNS服务器,找到服务器主机,向服务器发出一个请求,服务器经过解析之后,发送给用户的浏览器 HTML.JS.CSS 等文件,浏览器解析出来,用户便可以看到形形色色的图片了. 因此,用户看到的网页实质是由 HTML 代码构成的,爬虫爬来的便是这些内容

Python3 基础 —— 模块 Module 介绍

1.模块的作用 在交互模式下输出的变量和函数定义,一旦终端重启后,这些定义就都不存在了,为了持久保存这些变量.函数等的定义,Python中引入了模块(Module)的概念.一个Python模块其实就是一个脚本文件,具有后缀".py",例如 hello.py 就是一个模块文件名,和普通文件一样可以被永久保存在本地存储磁盘中. 2.模块的内容 Python模块中存放的是一些程序代码,例如,变量定义.函数定义或是代码语句.下面是hello.py模块的内容,其中有一个变量 a,一个函数 fun

ASP.NET MVC +EasyUI 权限设计(三)基础模块

请注明转载地址:http://www.cnblogs.com/arhat 在上一章中呢,我们基本上搭建好了环境,那么本章我们就从基础模块开始写起.由于用户,角色,动作三个当中,都是依赖与动作的,所以本章我们从动作开始做起,先把这个基础模块建立起来,然后才能把用户,角色和动作关联起来形成权限. 首先建立一个新的Controller为ActionController,为其Index方法创建一个视图文件,由于这样的视图文件太多了,而且重复性的代码也比较多,所以我们把共有的部分移植到Views/Shar

Puppet 通过基础模块、类、节点正则表达式批量管理Apache服务器

=> 创建httpd基础模块 # mkdir /etc/puppet/modules/httpd/{files,manifests,templates} -pv  # tree /etc/puppet/modules/httpd/ /etc/puppet/modules/httpd/ ├── files  //基础模块所调用的配置文件,agent可以通过puppet协议将files目录所定义的文件下载到本地. ├── manifests   //主要存放基础模块所使用的类文件及相关资源,如ini

Ansible 安装 及 基础模块介绍

ansible 介绍 Ansible基于Python开发,集合了众多优秀运维工具的优点,实现了批量运行命令部署程序.配置系统等功能.默认通过SSH协议进行远程命令执行或下发配置,无需部署任何客户端代理软件,从而使得自动化环境部署变得更加简单.可同时支持多台主机并行管理,使得管理主机更加便捷. ansible 安装 在管理端与 被管理端都要安装 yum install -y epel-release ##安装epel源 yum install ansible -y ansible --versio