python爬虫添加请求头代码实例

yipeiwu_com6年前Python爬虫

这篇文章主要介绍了python爬虫添加请求头代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

request

import requests


headers = {
  # 'Accept': 'application/json, text/javascript, */*; q=0.01',
  # 'Accept': '*/*',
  # 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7',
  # 'Cache-Control': 'no-cache',
  # 'accept-encoding': 'gzip, deflate, br',
  'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',
  'Referer': 'https://www.google.com/'
}

resp = requests.get('http://httpbin.org/get', headers=headers)
print(resp.content)

urllib

import urllib, urllib2
def get_page_source(url):
  headers = {'Accept': '*/*',
        'Accept-Language': 'en-US,en;q=0.8',
        'Cache-Control': 'max-age=0',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36',
        'Connection': 'keep-alive',
        'Referer': 'http://www.baidu.com/'
        }
  req = urllib2.Request(url, None, headers)
  response = urllib2.urlopen(req)
  page_source = response.read()
  return page_source

phantomjs请求页面

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
def get_headers_driver():
  desire = DesiredCapabilities.PHANTOMJS.copy()
  headers = {'Accept': '*/*',
        'Accept-Language': 'en-US,en;q=0.8',
        'Cache-Control': 'max-age=0',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36',
        'Connection': 'keep-alive',
        'Referer': 'http://www.baidu.com/'
        }
  for key, value in headers.iteritems():
    desire['phantomjs.page.customHeaders.{}'.format(key)] = value
  driver = webdriver.PhantomJS(desired_capabilities=desire, service_args=['--load-images=yes'])#将yes改成no可以让浏览器不加载图片
  return driver

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python3爬虫怎样构建请求header

python3爬虫怎样构建请求header

写一个爬虫首先就是学会设置请求头header,这样才可以伪装成浏览器。下面小编我就来给大家简单分析一下python3怎样构建一个爬虫的请求头header。 1、python3跟2有了细微...

python爬虫实例详解

python爬虫实例详解

本篇博文主要讲解Python爬虫实例,重点包括爬虫技术架构,组成爬虫的关键模块:URL管理器、HTML下载器和HTML解析器。 爬虫简单架构 程序入口函数(爬虫调度段) #codi...

详解python selenium 爬取网易云音乐歌单名

详解python selenium 爬取网易云音乐歌单名

目标网站: 首先获取第一页的数据,这里关键要切换到iframe里 打印一下 获取剩下的页数,这里在点击下一页之前需要设置一个延迟,不然会报错。 结果: 一共37页,爬取完...

python使用tornado实现简单爬虫

本文实例为大家分享了python使用tornado实现简单爬虫的具体代码,供大家参考,具体内容如下 代码在官方文档的示例代码中有,但是作为一个tornado新手来说阅读起来还是有点困难的...

Python3环境安装Scrapy爬虫框架过程及常见错误

Windows •安装lxml 最好的安装方式是通过wheel文件来安装,http://www.lfd.uci.edu/~gohlke/pythonlibs/,从该网站找到l...