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

yipeiwu_com4年前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设计】。

相关文章

讲解Python的Scrapy爬虫框架使用代理进行采集的方法

1.在Scrapy工程下新建“middlewares.py” # Importing base64 library because we'll need it ONLY in cas...

python制作花瓣网美女图片爬虫

花瓣图片的加载使用了延迟加载的技术,源代码只能下载20多张图片,修改后基本能下载所有的了,只是速度有点慢,后面再优化下 import urllib, urllib2, re, sys...

python网络爬虫 CrawlSpider使用详解

CrawlSpider 作用:用于进行全站数据爬取 CrawlSpider就是Spider的一个子类 如何新建一个基于CrawlSpider的爬虫文件 sc...

Python爬虫获取图片并下载保存至本地的实例

1、抓取煎蛋网上的图片。 2、代码如下: import urllib.request import os #to open the url def url_open(url): r...

Python爬取腾讯视频评论的思路详解

Python爬取腾讯视频评论的思路详解

一、前提条件 安装了Fiddler了(用于抓包分析) 谷歌或火狐浏览器 如果是谷歌浏览器,还需要给谷歌浏览器安装一个SwitchyOmega插件,用于代理服务器 有Py...