requests.get()参数

2023-05-16

查询参数-params

1.参数类型

  字典,字典中键值对作为查询参数

2.使用方法


1、res = requests.get(url,params=params,headers=headers)
2、特点: 
   * url为基准的url地址,不包含查询参数
   * 该方法会自动对params字典编码,然后和url拼接  

3.示例


import requests

baseurl = 'http://tieba.baidu.com/f?'
params = {
  'kw' : '赵丽颖吧',
  'pn' : '50'
}
headers = {'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3)'}
# 自动对params进行编码,然后自动和url进行拼接,去发请求
res = requests.get(baseurl,params=params,headers=headers)
res.encoding = 'utf-8'
print(res.text)  

web客户端验证 参数-auth

1.作用类型


1、针对于需要web客户端用户名密码认证的网站
2、auth = ('username','password')  

2.通过用户名账号密码获取笔记名称案例


import requests
from lxml import etree
import os

class NoteSpider(object):
    def __init__(self):
        self.url = 'http://code.com.cn/Code/aid1904/redis/'
        self.headers = {'User-Agent':'Mozilla/5.0'}
        self.auth = ('code','code_2013')

    # 获取
    def get_html(self):
        html = requests.get(url=self.url,auth=self.auth,headers=self.headers).text
        return html

    # 解析提取数据 + 把笔记压缩包下载完成
    def parse_page(self):
        html = self.get_html()
        xpath_bds = '//a/@href'
        parse_html = etree.HTML(html)
        # r_list : ['../','day01','day02','redis_day01.zip']
        r_list = parse_html.xpath(xpath_bds)
        for r in r_list:
            if r.endswith('zip') or r.endswith('rar'):
                print(r)

if __name__ == '__main__':
    spider = NoteSpider()
    spider.parse_page()  

思考:爬取具体的笔记文件?


import requests
from lxml import etree
import os

class NoteSpider(object):
    def __init__(self):
        self.url = 'http://code.com.cn/Code/redis/'
        self.headers = {'User-Agent':'Mozilla/5.0'}
        self.auth = ('code','code_2013')

    # 获取
    def get_html(self):
        html = requests.get(url=self.url,auth=self.auth,headers=self.headers).text
        return html

    # 解析提取数据 + 把笔记压缩包下载完成
    def parse_page(self):
        html = self.get_html()
        xpath_bds = '//a/@href'
        parse_html = etree.HTML(html)
        # r_list : ['../','day01','day02','redis_day01.zip']
        r_list = parse_html.xpath(xpath_bds)
        for r in r_list:
            if r.endswith('zip') or r.endswith('rar'):
                file_url = self.url + r
                self.save_files(file_url,r)

    def save_files(self,file_url,r):
        html_content = requests.get(file_url,headers=self.headers,auth=self.auth).content
        # 判断保存路径是否存在
        directory = '/home/redis/'
        filename = directory + r
     #适用频率很高
     #if not os.path.exists('路径'):
     #  os.makedirs('路径') 可递归创建
     #  os.mkdir('路径')不能递归创建
if not os.path.exists(directory): os.makedirs(directory)
     with open(filename,
'wb') as f: f.write(html_content) print(r,'下载成功') if __name__ == '__main__': spider = NoteSpider() spider.parse_page()

SSL证书认证参数-verify

1.适用网站及场景


1、适用网站: https类型网站但是没有经过 证书认证机构 认证的网站
2、适用场景: 抛出 SSLError 异常则考虑使用此参数  

2.参数类型


1、verify=True(默认)   : 检查证书认证
2、verify=False(常用): 忽略证书认证
# 示例
response = requests.get(
    url=url,
    params=params,
    headers=headers,
    verify=False
)  

代理参数-proxies 

1.定义


1、定义: 代替你原来的IP地址去对接网络的IP地址。
2、作用: 隐藏自身真实IP,避免被封。  

2.普通代理

  获取代理IP网站


西刺代理、快代理、全网代理、代理精灵、... ...   

  参数类型


1、语法结构
       proxies = {
           '协议':'协议://IP:端口号'
       }
2、示例
    proxies = {
        'http':'http://IP:端口号',
        'https':'https://IP:端口号'
    }  

  示例代码

    (1)使用免费普通代理IP访问测试网站: http://httpbin.org/get


import requests

url = 'http://httpbin.org/get'
headers = {
    'User-Agent':'Mozilla/5.0'
}
# 定义代理,在代理IP网站中查找免费代理IP
proxies = {
    'http':'http://112.85.164.220:9999',
    'https':'https://112.85.164.220:9999'
}
html = requests.get(url,proxies=proxies,headers=headers,timeout=5).text
print(html)  

    考: 建立一个自己的代理IP池,随时更新用来抓取网站数据


1.从代理IP网站上,抓取免费的代理IP
2.测试抓取的IP,可用的保存在文件中  

    (2)一个获取收费开放代理的接口


# 获取开放代理的接口
import requests

def test_ip(ip):
    url = 'http://www.baidu.com/'
    proxies = {
        'http':'http://{}'.format(ip),
        'https':'https://{}'.format(ip),
    }
    try:
        res = requests.get(url=url,proxies=proxies,timeout=8)
        if res.status_code == 200:
               return True
       except Exception as e:
               return False

# 提取代理IP
def get_ip_list():
  api_url = 'http://dev.kdlapi.com/api/getproxy/?orderid=946562662041898&num=100&protocol=1&method=2&an_an=1&an_ha=1&sep=2'
  html = requests.get(api_url).content.decode('utf-8','ignore')
  ip_port_list = html.split('\n')

  for ip in ip_port_list:
    with open('proxy_ip.txt','a') as f:
        if test_ip(ip):
            f.write(ip + '\n')

if __name__ == '__main__':
    get_ip_list()  
实现代码

    (3)使用随机收费开放代理IP写爬虫


import random
import requests

class BaiduSpider(object):
    def __init__(self):
        self.url = 'http://www.baidu.com/'
        self.headers = {'User-Agent' : 'Mozilla/5.0'}
        self.blag = 1

    def get_proxies(self):
        with open('proxy_ip.txt','r') as f:
            #f.readlines:['1.1.1.1:111\n','2.2.2.2:22\n']
            result = f.readlines()
        #[:-1] -> 切掉ip,port后的\n
        proxy_ip = random.choice(result)[:-1]
        proxy_ip = {
            'http':'http://{}'.format(proxy_ip),
            'https': 'https://{}'.format(proxy_ip)
        }
        return proxy_ip

    def get_html(self):
        proxies = self.get_proxies()
        if self.blag <= 3:
            try:
                html = requests.get(url=self.url,proxies=proxies,headers=self.headers,timeout=5).text
                print(html)
            except Exception as e:
                print('Retry')
                self.blag += 1
                self.get_html()

if __name__ == '__main__':
    spider = BaiduSpider()
    spider.get_html()  
实现代码

3.私密代理

  语法格式


1、语法结构
proxies = {
    '协议':'协议://用户名:密码@IP:端口号'
}

2、示例
proxies = {
    'http':'http://用户名:密码@IP:端口号',
    'https':'https://用户名:密码@IP:端口号'
}  

  示例代码


import requests
url = 'http://httpbin.org/get'
proxies = {
    'http': 'http://309435365:szayclhp@106.75.71.140:16816',
    'https':'https://309435365:szayclhp@106.75.71.140:16816',
}
headers = {
    'User-Agent' : 'Mozilla/5.0',
}

html = requests.get(url,proxies=proxies,headers=headers,timeout=5).text
print(html)  

urllib和urllib2关系


#python2
urllib :URL地址编码
urllib2:请求
#python3 - 把python2中urllib和urllib2合并
urllib.parse:编码
urllib.requests: 请求  

控制台抓包

打开方式几常用选项


1、打开浏览器,F12打开控制台,找到Network选项卡
2、控制台常用选项
   1、Network: 抓取网络数据包
        1、ALL: 抓取所有的网络数据包
        2、XHR:抓取异步加载的网络数据包
        3、JS : 抓取所有的JS文件
   2、Sources: 格式化输出并打断点调试JavaScript代码,助于分析爬虫中一些参数
   3、Console: 交互模式,可对JavaScript中的代码进行测试
3、抓取具体网络数据包后
   1、单击左侧网络数据包地址,进入数据包详情,查看右侧
   2、右侧:
       1、Headers: 整个请求信息
            General、Response Headers、Request Headers、Query String、Form Data
       2、Preview: 对响应内容进行预览
       3、Response:响应内容  

 

转载于:https://www.cnblogs.com/maplethefox/p/11348491.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

requests.get()参数 的相关文章

  • Angular2 - 将 POST 与 angular-in-memory-web-api 一起使用

    我正在使用 Angular 2 的 angular in memory web api 到目前为止 我只使用了 GET 调用 而且运行良好 我要调用的 API 仅使用 POST 调用 因此我开始将 GET 调用重写为 POST 调用 但随后
  • 使用 Java 套接字进行 GET 请求

    我正在编写一个简单的程序来向特定的 url 发送 get 请求 http badunetworks com about http badunetworks com about 如果我将请求发送到 则该请求有效http badunetwork
  • Javascript 从服务器获取纯文本

    我想从我的服务器接收纯文本 或任何文档 作为字符串变量 例如在警报中显示它我尝试了这个解决方案 wordsurl http alpha test function ButtonClicked showsentence wordsurl fu
  • 我可以 POST 和 GET 到同一个 PHP 页面吗

    例如 我想知道是否可以在同一个 php 页面上进行 GET 和 POST 我想将数据发送到 http www example com my php 所以首先是 GET http www example com my php task dos
  • 在嵌套有序字典 python 中查找给定键的值

    我试图从嵌套的 OrderedDict 中查找给定键的值 关键点 我不知道这个字典会嵌套多深 我正在寻找的键的名称是不变的 它将位于字典中的某个位置 我想返回本例中名为 powerpoint color 的键的值 mydict Ordere
  • 未捕获的类型错误:未定义不是 indexOf 上的函数

    我目前有此代码来检查特定 ID 的网站 URL GET 选项 但每当运行此代码时 我都会收到一个奇怪的错误 Uncaught TypeError Undefined is not a function 这是我的代码 如果我能得到关于这个问题
  • 如何在android sdk中从图库中获取图像并将其显示到屏幕上

    我想知道如何从图库中获取预先保存的图像 然后将其显示到屏幕上 任何教程 有用的链接和信息将不胜感激 如果您希望我进一步解释任何内容 请询问 Intent photoPickerIntent new Intent Intent ACTION
  • 第301章

    Problem 访客打开网址website com i 133r534 213213 12312312但此网址不再有效 需要将其转发到website com 视频 133r534 213213 12312312 我尝试过的 在过去的几个小时
  • 在弹性搜索中使用 GET/POST 时的不同结果

    我正在通过 Elastic Search Head 插件尝试弹性搜索 当我通过 POST 提交查询时 结果符合预期 但是 当我使用 GET 尝试相同的查询时 我总是会返回索引中的所有值 那么 如何通过 GET 将查询传递到弹性搜索服务器 以
  • 使标签充当输入按钮

    我怎样才能做一个 a href http test com tag test Test a 就像表单按钮一样 通过充当表单按钮 我的意思是 当单击链接执行操作时method get 或 post 以便能够通过 get 或 post 捕获它
  • 阻止通过 GET 传递“提交”按钮值?

    我正在尝试通过 GET 传递表单信息 这很重要 这样人们就可以将表单选择中过滤后的数据发送给其他人 问题是 使用下面的代码 它不仅传递过滤器信息 还传递提交表单值 如下所示 index php month filter Feb year f
  • 如何通过 Ruby 中的代理获取带有用户代理和超时的 URL?

    如果我需要通过某些方式获取 URL 我该如何获取 URLproxy 它必须有一个timeout最大 n 秒 和一个用户代理 require nokogiri require net http require rexml document d
  • 在 Python 中将 GET 更改为 POST (Flask)

    我正在尝试创建一个简单的应用程序 其中在服务器上生成整数数组并将其发送到客户端 以下是 app py 中的一些示例 工作 代码 from flask import Flask render template request url for
  • AngularJS - 在等待数据/数据计算时加载图标

    我有一个简单的 Angular http get app factory countriesService function http return getCountryData function done http get resourc
  • Spotify:使用网络 API 登录不接受重定向 URL

    我正在尝试使用 Web API 登录 Spotify 因为我不需要会话对象 在我的授权方法中 我需要传入重定向 url 但 GET 请求中不接受 iOS 重定向 url 的格式化方式 func authorize create the ur
  • net::ERR_CONNECTION_REFUSED 错误 jQuery ajax node.js

    当日期输入中的日期更改发生得非常快时 就会发生此错误 如果我每 2 秒以上更改一次日期 效果就很好 但是当日期输入更改得非常快时 它会出现以下错误 简而言之 只有当第一个请求之后很快发出下一个请求时 才会发生此错误 我花了几个小时在 SO
  • Memcached的get和put方法是线程安全的吗

    多线程环境下memcached中的key是否有可能出现乱码 如果是这样 如何以最短的同步时间避免它 使用Java客户端访问memcached服务器 不会 Memcache 将返回某人之前写入的值 而不是乱码 如果您获取 修改 放置 则无法保
  • ajax“GET”调用返回 jsonp 正常,但回调产生“未定义”数据

    我正在使用来自 html 页面的 ajax jquery 调用来访问跨域 Web 服务 虽然我可以使用 firebug 查看 jsonp 数据 但我无法将其加载到变量中 甚至无法显示它 出于调试目的 尝试使用 jsonpCallback s
  • jQuery 提取 div 内的文本,但不在 p 标签中

    在下面的代码中 我想将一个变量放入文本中div但不是里面的东西p tag div class review content merchant review content I want to grab this text p class r
  • 如何在 PHP 中使用 cURL 发出同时包含 GET 和 POST 参数的请求?

    其他人已经问过如何从 perl java bash 等执行此操作 但我需要在 PHP 中执行此操作 并且我没有看到任何已提出的专门与 PHP 相关的问题 或包含 PHP 的答案 My code ch curl init url curl s

随机推荐