zoukankan      html  css  js  c++  java
  • 修改请求头 -> 设置连接超时 -> 延迟提交数据

     一.修改请求头:

     应对反爬虫措施可以修改请求头来模拟正常的访问,Request 中有个 headers 参数,可通过 如下两种方法进行设置:

    (1)把请求头都塞到字典里,在实例化 Request对象的时候传入;

    (2)通过 Request对象的 add_header()方法一个个添加。 


     1 # -*- coding: utf-8 -*-
     2 """
     3 Created on Tue Apr  7 15:55:53 2020
     4 
     5 @author: ZKYAAA
     6 """
     7 import urllib.request
     8 # 修改头信息
     9 novel_url = "http://www.santostang.com/"
    10 headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '
    11                          'AppleWebKit/537.36 (KHTML, like Gecko)'
    12                          ' Chrome/63.0.3239.84 Safari/537.36',
    13            'Referer': 'http://www.baidu.com',
    14            'Connection': 'keep-alive'}
    15 novel_req = urllib.request.Request(novel_url, headers=headers)
    16 novel_resp = urllib.request.urlopen(novel_req)
    17 print(novel_resp.read().decode('utf-8'))

      二.设置连接超时 

    (1)参考:https://blog.csdn.net/weixin_41987744/article/details/99637199

    (2)urlopen()函数中有一个可选参数 timeout,单位为秒,作用是如果请求超出了这个时间 还没有得到响应,就会抛出异常。如果不设置,会使用全局默认时间;

             timeout参数未设置时可能会导致hangg问题,设置timeout=60(单位:秒),在不断的”断网-联网“冲击下,hang 不出现问题

    1 urllib.request.urlopen(novel_req, timeout=20) 
  • 相关阅读:
    自定义 ClassLoader
    HashCode 解析
    Unsafe与CAS
    ReentrantLock实现原理深入探究
    javaNIO:选择器--实践 Selector
    javaNIO:选择器--理论 Selector
    javaNIO:Socket通道
    CentOs 7 kong 2.3.X oss 自定义插件
    CentOs 7 kong 2.3.X oss 部署安装
    CentOS7 yum安装、配置PostgreSQL 9.6
  • 原文地址:https://www.cnblogs.com/ZKYAAA/p/12654265.html
Copyright © 2011-2022 走看看