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

相关文章

Python 制作糗事百科爬虫实例

Python 制作糗事百科爬虫实例

早上起来闲来无事做,莫名其妙的就弹出了糗事百科的段子,转念一想既然你送上门来,那我就写个爬虫到你网站上爬一爬吧,一来当做练练手,二来也算找点乐子。 其实这两天也正在接触数据库的内容,可以...

python网络爬虫采集联想词示例

python爬虫_采集联想词代码 复制代码 代码如下:#coding:utf-8import urllib2import urllibimport reimport timefrom r...

Python爬取APP下载链接的实现方法

Python爬取APP下载链接的实现方法

首先是准备工作 Python 2.7.11:下载python Pycharm:下载Pycharm 其中python2和python3目前同步发行,我这里使用的是python2作为环境。P...

深度剖析使用python抓取网页正文的源码

本方法是基于文本密度的方法,最初的想法来源于哈工大的《基于行块分布函数的通用网页正文抽取算法》,本文基于此进行一些小修改。 约定:    &nbs...

使用python爬虫获取黄金价格的核心代码

使用python爬虫获取黄金价格的核心代码

继续练手,根据之前获取汽油价格的方式获取了金价,暂时没钱投资,看看而已 #!/usr/bin/env python # -*- coding: utf-8 -*- """ 获取每天黄...