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

yipeiwu_com5年前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微医挂号网医生数据抓取

1. 写在前面 今天要抓取的一个网站叫做微医网站,地址为 https://www.guahao.com/ ,我们将通过python3爬虫抓取这个网址,然后数据存储到CSV里面,为后面的一...

Python网络爬虫出现乱码问题的解决方法

关于爬虫乱码有很多各式各样的问题,这里不仅是中文乱码,编码转换、还包括一些如日文、韩文 、俄文、藏文之类的乱码处理,因为解决方式是一致的,故在此统一说明。 网络爬虫出现乱码的原因 源...

使用python 爬虫抓站的一些技巧总结

使用python 爬虫抓站的一些技巧总结

学用python也有3个多月了,用得最多的还是各类爬虫脚本:写过抓代理本机验证的脚本,写过在discuz论坛中自动登录自动发贴的脚本,写过自动收邮件的脚本,写过简单的验证码识别的脚本,本...

Python常用的爬虫技巧总结

用python也差不多一年多了,python应用最多的场景还是web快速开发、爬虫、自动化运维:写过简单网站、写过自动发帖脚本、写过收发邮件脚本、写过简单验证码识别脚本。 爬虫在开发过程...

Python使用Selenium+BeautifulSoup爬取淘宝搜索页

使用Selenium驱动chrome页面,获得淘宝信息并用BeautifulSoup分析得到结果。 使用Selenium时注意页面的加载判断,以及加载超时的异常处理。 impor...