Python爬虫headers处理及网络超时问题解决方案

1、请求headers处理

  我们有时请求服务器时,无论get或post请求,会出现403错误,这是因为服务器拒绝了你的访问,这时我们可以通过模拟浏览器的头部信息进行访问,这样就可以解决反爬设置的问题。

import requests
# 创建需要爬取网页的地址
url = 'https://www.baidu.com/'
# 创建头部信息
headers = {'User-Agent':'OW64; rv:59.0) Gecko/20100101 Firefox/59.0'}
# 发送网络请求
response = requests.get(url, headers=headers)
# 以字节流形式打印网页源码
print(response.content)

结果:

b'<!DOCTYPE html><!--STATUS OK-->\n\n\n  \n  \n              <html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta content="always" name="referrer"><meta name="theme-color" content="#2932e1"><meta name="description" content="\xe5\x85\xa8\xe7\x90\x83\xe6\x9c\x80\xe5\xa4\xa7\xe7\x9a\x84\xe4\xb8\xad\xe6\x96\x87\xe6\x90\x9c\xe7\xb4\xa2\xe5\xbc\x95\xe6\x93\x8e\xe3\x80\x81\xe8\x87\xb4\xe5\x8a\x9b\xe4\xba\x8e\xe8\xae\xa9\xe7\xbd\x91\xe6\xb0\x91\xe6\x9b\xb4\xe4\xbe\xbf\xe6\x8d\xb7\xe5\x9c\xb0\xe8\x8e\xb7\xe5\x8f\x96\xe4\xbf\xa1\xe6\x81\xaf\xef\xbc\x8c\xe6\x89\xbe\xe5\x88\xb0\xe6\x89\x80\xe6\xb1\x82\xe3\x80\x82\xe7\x99\xbe\xe5\xba\xa6\xe8\xb6\x85\xe8\xbf\x87\xe5\x8d\x83\xe4\xba\xbf\xe7\x9a\x84\xe4\xb8\xad\xe6\x96\x87\xe7\xbd\x91\xe9\xa1\xb5\xe6\x95\xb0\xe6\x8d\xae\xe5\xba\x93\xef\xbc\x8c\xe5\x8f\xaf\xe4\xbb\xa5\xe7\x9e\xac\xe9\x97\xb4\xe6\x89\xbe\xe5\x88\xb0\xe7\x9b\xb8\xe5\x85\xb3\xe7\x9a\x84\xe6\x90\x9c\xe7\xb4\xa2\xe7\xbb\x93\xe6\x9e\x9c\xe3\x80\x82"><link rel="shortcut icon" href="/favicon.ico" rel="external nofollow" type="image/x-icon" /><link rel="search" type="application/opensearchdescription+xml" href="/content-search.xml" rel="external nofollow" title="\xe7\x99\xbe\xe5\xba\xa6\xe6\x90\x9c\xe7\xb4\xa2" /><link rel="icon" sizes="any" mask href="//www.baidu.com/img/baidu_85beaf5496f291521eb75ba38eacbd87.svg" rel="external nofollow" ><link rel="dns-prefetch" href="//dss0.bdstatic.com" rel="external nofollow" /><link rel="dns-prefetch" href="//dss1.bdstatic.com" rel="external nofollow" /><link rel="dns-prefetch" href="//ss1.bdstatic.com" rel="external nofollow" /><link rel="dns-prefetch" href="//sp0.baidu.com" rel="external nofollow" /><link rel="dns-prefetch" href="//sp1.baidu.com" rel="external nofollow" /><link rel="dns-prefetch" href="//sp2.baidu.com" rel="external nofollow" />

2、网络超时问题

  在访问一个网页时,如果该网页长时间未响应,系统就会判断该网页超时,而无法打开网页。下面通过代码来模拟一个网络超时的现象。

import requests
# 循环发送请求50次
for a in range(1, 50):
  # 捕获异常
  try:
    # 设置超时为0.5秒
    response = requests.get('https://www.baidu.com/', timeout=0.5)
    # 打印状态码
    print(response.status_code)
  # 捕获异常
  except Exception as e:
    # 打印异常信息
    print('异常'+str(e))

结果:

200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200

以上代码中,模拟进行了50次循环请求,设置超时时间为0.5秒,在0.5秒内服务器未作出相应视为超时,程序会将超时信息打印在控制台中。

  说起网络异常信息,requests模块同样提供了三种常见的网络异常类,示例代码如下:

import requests
# 导入requests.exceptions模块中的三种异常类
from requests.exceptions import ReadTimeout,HTTPError,RequestException
# 循环发送请求50次
for a in range(1, 50):
  # 捕获异常
  try:
    # 设置超时为0.5秒
    response = requests.get('https://www.baidu.com/', timeout=0.5)
    # 打印状态码
    print(response.status_code)
  # 超时异常
  except ReadTimeout:
    print('timeout')
  # HTTP异常
  except HTTPError:
    print('httperror')
  # 请求异常
  except RequestException:
    print('reqerror')

结果:

200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200
200

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Python selenium爬虫实现定时任务过程解析

    现在需要启动一个selenium的爬虫,使用火狐驱动+多线程,大家都明白的,现在电脑管家显示CPU占用率20%,启动selenium后不停的开启浏览器+多线程, 好,没过5分钟,CPU占用率直接拉到90%+,电脑卡到飞起,定时程序虽然还在运行,但是已经类似于待机状态, 是不是突然感觉到面对电脑卡死,第一反应:卧槽,这个lj电脑,这么程序都跑不起来,我还写这么多代码,*****!! 是吧,接下来上代码,具体功能,请自信查阅相关资料深造: from datetime import datetime

  • 使用Python爬虫库requests发送请求、传递URL参数、定制headers

    首先我们先引入requests模块 import requests 一.发送请求 r = requests.get('https://api.github.com/events') # GET请求 r = requests.post('http://httpbin.org/post', data = {'key':'value'}) # POST请求 r = requests.put('http://httpbin.org/put', data = {'key':'value'}) # PUT请

  • Python使用Chrome插件实现爬虫过程图解

    做电商时,消费者对商品的评论是很重要的,但是不会写代码怎么办?这里有个Chrome插件可以做到简单的数据爬取,一句代码都不用写.下面给大家展示部分抓取后的数据: 可以看到,抓取的地址,评论人,评论内容,时间,产品颜色都已经抓取下来了.那么,爬取这些数据需要哪些工具呢?就两个: 1. Chrome浏览器: 2. 插件:Web Scraper 插件下载地址:https://chromecj.com/productivity/2018-05/942.html 最后,如果你想自己动手抓取一下,这里是这次

  • 为什么说python适合写爬虫

    抓取网页本身的接口 相比与其他静态编程语言,如java,c#,C++,python抓取网页文档的接口更简洁:相比其他动态脚本语言,如perl,shell,python的urllib2包提供了较为完整的访问网页文档的API.(当然ruby也是很好的选择) 此外,抓取网页有时候需要模拟浏览器的行为,很多网站对于生硬的爬虫抓取都是封杀的.这是我们需要模拟user agent的行为构造合适的请求,譬如模拟用户登陆.模拟session/cookie的存储和设置.在python里都有非常优秀的第三方包帮你搞

  • python爬虫headers设置后无效的解决方法

    此次遇到的是一个函数使用不熟练造成的问题,但有了分析工具后可以很快定位到问题(此处推荐一个非常棒的抓包工具fiddler) 正文如下: 在爬取某个app数据时(app上的数据都是由http请求的),用Fidder分析了请求信息,并把python的request header信息写在程序中进行请求数据 代码如下 import requests url = 'http://xxx?startDate=2017-10-19&endDate=2017-10-19&pageIndex=1&l

  • 使用python将请求的requests headers参数格式化方法

    如下所示: import json # 使用三引号将浏览器复制出来的requests headers参数赋值给一个变量 headers = """ Host: zhan.qq.com Proxy-Connection: keep-alive Content-Length: 799432 Pragma: no-cache Cache-Control: no-cache Origin: http://zhan.qq.com User-Agent: Mozilla/5.0 (Win

  • 解决python3 requests headers参数不能有中文的问题

    1 需求,heeaders 参数需要拼接中文参数param 解决如下 url = 'https://....search?keyword=' + param + '&templateId=&page=1&pageSize=10' headers = { "Accept": "application/json, text/javascript, */*; q=0.01", "Accept-Encoding": "g

  • Python爬虫:将headers请求头字符串转为字典的方法

    原生请求头字符串 raw_headers = """Host: open.tool.hexun.com Pragma: no-cache Cache-Control: no-cache User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36 Accept: */* Re

  • Python爬虫获取页面所有URL链接过程详解

    如何获取一个页面内所有URL链接?在Python中可以使用urllib对网页进行爬取,然后利用Beautiful Soup对爬取的页面进行解析,提取出所有的URL. 什么是Beautiful Soup? Beautiful Soup提供一些简单的.python式的函数用来处理导航.搜索.修改分析树等功能.它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序. Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换

  • Python爬虫headers处理及网络超时问题解决方案

    1.请求headers处理 我们有时请求服务器时,无论get或post请求,会出现403错误,这是因为服务器拒绝了你的访问,这时我们可以通过模拟浏览器的头部信息进行访问,这样就可以解决反爬设置的问题. import requests # 创建需要爬取网页的地址 url = 'https://www.baidu.com/' # 创建头部信息 headers = {'User-Agent':'OW64; rv:59.0) Gecko/20100101 Firefox/59.0'} # 发送网络请求

  • Python selenium页面加载慢超时的解决方案

    开发环境: win10-64  python2.7.16  chrome77 from selenium import webdriver driver = webdriver.Chrome(executable_path='chromedriver.exe') driver.get('http://全部加载完成超级慢的网站') user = 'abc' pwd = '123 driver.find_element_by_id('email').send_keys(user) driver.fi

  • python爬虫之urllib,伪装,超时设置,异常处理的方法

    Urllib 1. Urllib.request.urlopen().read().decode() 返回一个二进制的对象,对这个对象进行read()操作,可以得到一个包含网页的二进制字符串,然后用decode()解码成html源码 2. urlretrieve() 将一个网页爬取到本地 3. urlclearup() 清除 urlretrieve()所产生的缓存 4. info() 返回一个httpMessage对象,表示远程服务器的头信息 5. getcode() 获取当前网页的状态码 20

  • Python爬虫实例_城市公交网络站点数据的爬取方法

    爬取的站点:http://beijing.8684.cn/ (1)环境配置,直接上代码: # -*- coding: utf-8 -*- import requests ##导入requests from bs4 import BeautifulSoup ##导入bs4中的BeautifulSoup import os headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,

  • python爬虫多次请求超时的几种重试方法(6种)

    第一种方法 headers = Dict() url = 'https://www.baidu.com' try: proxies = None response = requests.get(url, headers=headers, verify=False, proxies=None, timeout=3) except: # logdebug('requests failed one time') try: proxies = None response = requests.get(u

  • python爬虫系列网络请求案例详解

    学习了之前的基础和爬虫基础之后,我们要开始学习网络请求了. 先来看看urllib urllib的介绍 urllib是Python自带的标准库中用于网络请求的库,无需安装,直接引用即可. 主要用来做爬虫开发,API数据获取和测试中使用. urllib库的四大模块: urllib.request: 用于打开和读取url urllib.error : 包含提出的例外,urllib.request urllib.parse:用于解析url urllib.robotparser:用于解析robots.tx

  • Python爬虫之网络请求

    目录 1.IP代理 2.Cookie 3.异常处理 1.IP代理 某些网站会检测一段时间内某IP的访问次数,若访问次数过多会禁止访问,这时需要设置一些代理服务器,每隔一段时间换一个代理.IP代理的分类: ①透明代理:目标网站可以得知使用了代理以及源IP地址,显然这不符合要求: ②匿名代理:目标网站知道使用了代理,但不知道源IP地址: ③高匿代理:最保险的方式,目标网站既不知道使用了代理,也不知道源IP地址. 2.Cookie 解决http的无状态性,第一次向服务器发送请求时,服务器生成Cooki

  • 使用python爬虫实现网络股票信息爬取的demo

    实例如下所示: import requests from bs4 import BeautifulSoup import traceback import re def getHTMLText(url): try: r = requests.get(url) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: return "" def getStockList(lst, stockUR

  • python爬虫超时的处理的实例

    如下所示: #coding:utf-8 ''''' Created on 2014-7-24 @author: Administrator ''' import urllib2 try: url = "http://www.baidu.com" f = urllib2.urlopen(url, timeout=0) #timeout设置超时的时间 result = f.read() # print len(result) print result except Exception,e:

随机推荐