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

requests模块的高级应用

时间:2020-05-05 23:18:30      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:url   pwm   imp   cio   图片验证码   serve   自动生成   lis   json   

requests抓取数据报错

- HttpConnectinPool:
    - 原因:
        - 1.短时间内发起了高频的请求导致ip被禁
        - 2.http连接池中的连接资源被耗尽
    - 解决:
        - 1.代理
        - 2.headers中加入Conection:“close”

代理服务器

- 代理:代理服务器,可以接受请求然后将其转发。
- 匿名度
    - 高匿:既不知道请求者使用了代理,也不知道请求者的真实IP
    - 匿名:知道请求者使用了代理,但是不知道请求者的真实IP
    - 透明:知道请求者使用了代理并且知道请求者的真实IP
- 类型:
    - http
    - https
- 免费代理:
    - www.goubanjia.com
    - 快代理
    - 西祠代理
    - http://http.zhiliandaili.cn/
    

在requests.get()方法中使用代理IP

import requests
headers = {
    User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36
}
url = https://www.baidu.com/s?wd=ip
page_text = requests.get(url,headers=headers,proxies={https:111.231.94.44:8888}).text
with open(ip.html,w,encoding=utf-8) as fp:
    fp.write(page_text)

手动生成代理池

import random
proxy_list = [
    {https:121.231.94.44:8888},
    {https:131.231.94.44:8888},
    {https:141.231.94.44:8888}
]
url = https://www.baidu.com/s?wd=ip
page_text = requests.get(url,headers=headers,proxies=random.choice(proxy_list)).text
with open(ip.html,w,encoding=utf-8) as fp:
    fp.write(page_text)

从网上抓取代理IP自动生成代理池

from lxml import etree
import random

#从代理精灵中提取代理ip(用于爬取免费代理IP的代理IP是付费的)
ip_url = http://t.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&groupid=0&qty=4&time=1&pro=&city=&port=1&format=html&ss=5&css=&dt=1&specialTxt=3&specialJson=&usertype=2
page_text = requests.get(ip_url,headers=headers).text
tree = etree.HTML(page_text)
ip_list = tree.xpath(//body//text())
print(ip_list)

#爬取西祠代理
headers = {
    User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36,
    Connection:"close"
}
url = https://www.xicidaili.com/nn/%d
proxy_list_http = []
proxy_list_https = []
for page in range(1,20):
    new_url = format(url%page)
    ip_port = random.choice(ip_list)
    page_text = requests.get(new_url,headers=headers,proxies={https:ip_port}).text
    tree = etree.HTML(page_text)
    #tbody不可以出现在xpath表达式中
    tr_list = tree.xpath(//*[@id="ip_list"]//tr)[1:]
    for tr in tr_list:
        ip = tr.xpath(./td[2]/text())[0]
        port = tr.xpath(./td[3]/text())[0]
        t_type = tr.xpath(./td[6]/text())[0]
        ips = ip+:+port
        if t_type == HTTP:
            dic = {
                t_type: ips
            }
            proxy_list_http.append(dic)
        else:
            dic = {
                t_type:ips
            }
            proxy_list_https.append(dic)
print(len(proxy_list_http),len(proxy_list_https))


#检测代理IP是否可用
for ip in proxy_list_http:
    response = requests.get(https://www/sogou.com,headers=headers,proxies={https:ip})
    if response.status_code == 200:
        print(检测到了可用ip)

Cookie

- cookie的处理
    - 手动处理:将cookie封装到headers中
    - 自动处理:session对象。可以创建一个session对象,改对象可以像requests一样进行请求发送。不同之处在于如果在使用session进行请求发送的过程中产生了cookie,则cookie会被自动存储在session对象中。

示例1.1(不携带Cookie访问)

import requests
#对雪球网中的新闻数据进行爬取https://xueqiu.com/
url="https://xueqiu.com/"
headers = {
    User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36,
}
response_text=requests.get(url,headers).text
response_text

此时是获取不到网页的数据信息,因为如果想要访问页面的数据,需要携带Cookie数据。

示例1.2(手动添加Cookie后访问)

import requests
url="https://xueqiu.com/"
headers = {
    User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36,
    Cookie:"aliyungf_tc=AQAAAG6X1z3opwMAkLryeKCukrQNV62H; acw_tc=2760822e15886875892523578ed4228020edfe26c3c0eb41d7d9467d8bf6e3; xq_a_token=48575b79f8efa6d34166cc7bdc5abb09fd83ce63; xqat=48575b79f8efa6d34166cc7bdc5abb09fd83ce63; xq_r_token=7dcc6339975b01fbc2c14240ce55a3a20bdb7873; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOi0xLCJpc3MiOiJ1YyIsImV4cCI6MTU4OTY4MjczMCwiY3RtIjoxNTg4Njg3NTYzMDY1LCJjaWQiOiJkOWQwbjRBWnVwIn0.oXNGRbTOZfgChAFNq-BN9v7Q01-ogPgYI-nNDdasJKwSIF4TpfPgTZzRQ6evFHxCmX22GvrL-N7nCVwYTnWWn-7oB7K9d6dagYPja5uWqBNwI1qL7A5yP_SF4OG0meC2BSOU-gAt7whoE7DC-ChkJL0CJ5ZyqjNnYsl_EJjPUDMvEm0ex6surEHJW3uIfh15iIUYJKrjT5FxxjkyNe_C0KjIZXRgJMK77-rcTxlBxzHJkeCIsEKwpEYjKTWAJJYL4r-gC49wJvT_Y2WrdVOtQ9rXT2Q2_rHStT-zEBb9p55ZZakfHb9uzFadI7J1Zkl6w02ns8DVt-DKKRM5XRBg3A; u=691588687589257; Hm_lvt_1db88642e346389874251b5a1eded6e3=1588687591; device_id=24700f9f1986800ab4fcc880530dd0ed; s=co11ch62mg; __utma=1.206451581.1588687610.1588687610.1588687610.1; __utmc=1; __utmz=1.1588687610.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmt=1; __utmb=1.1.10.1588687610; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1588687614",
}
response_text=requests.get(url,headers=headers).text
response_text=response_text.encode("iso-8859-1").decode("utf-8")
response_text

此时可以获得页面数据信息,但是如果目标网站每次访问的Cookie是动态生成的,手动添加就行不通了。

示例1.3(使用Session对象自动获取并添加Cookie到请求信息中)

import requests
url="https://xueqiu.com/"
headers = {
    User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36,
}
session=requests.Session()
response_text=session.get(url,headers=headers).text
response_text=response_text.encode("iso-8859-1").decode("utf-8")
response_text

此时也是能够顺利取到网页数据。

自动登录中的图片验证码识别

 

requests模块的高级应用

标签:url   pwm   imp   cio   图片验证码   serve   自动生成   lis   json   

原文地址:https://www.cnblogs.com/sun-10387834/p/12833496.html

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