常见的请求头:

    host:网站的域名    比如:www.lagou.com

    content-type:请求数据的类型

    user-agent:发送请求的代理

    cookie:发送请求携带的cookie

    referer:上一次请求的地址

    Location:(响应头中)重定向的地址

爬取抽屉:

 

备注:最常用的一种反爬虫的方式,就是验证请求头中有没有携带user-agent,所有在爬取时要携带这个头请求

 

抽屉网的自动登录和查看个人页面

 

备注:请求的过程中要携带cookie,可以通过从response中获取cookies,借助requests模块中封装的方法,直接将请求返回的响应封装成一个dict的形式,通过  ret.cookies.get_dict()的方法。

 

自动登录GitHub

获取登录页面

爬虫示例

发送登录的post请求

发送post请求时是向https://github.com/session这个url发送的post的请求,请求数据中,除了必须的登录名和密码外,还需要commit参数和utf8参数,此外还有一个动态参数authenticity_token,每次发送请求,都会发生变化。那这个参数是怎么来的?

  一般这种参数要么隐藏在页面中,就像django中的csrf-token一样,要么是在js中动态的通过一定的算法生成。

  github中的authenticity_token参数是在页面中隐藏的一个参数。

爬虫示例

可以通过beautifulsoup直接解析出来

发送post请求必须携带cookies

爬虫示例

 

爬虫示例

 每次请求都会返回一个cookie,查看某个页面时,携带的请求要么是上一次的请求的cookie,要么是第一次访问页面的cookie,亦或者是两次或更多次cookie的结合。

代码示例:

import requests

from bs4 import BeautifulSoup


###################  发送登录的get请求,获得登录页面   ####################
ret = requests.get(
    url='https://github.com/login',

)

ret_cookie_dict = ret.cookies.get_dict()

# 获取请求页面中的authenticity_token参数

soup = BeautifulSoup(ret.text,'html.parser')
token = soup.find(name='input',attrs={'name':'authenticity_token'}).attrs.get('value')

#################  发送登录的post请求  ###########################333

ret1 = requests.post(
    url='https://github.com/session',
    headers={
        'Host': 'github.com',
        'Origin': 'https://github.com',
        'Pragma': 'no-cache',
        'Referer': 'https://github.com/login',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36'
    },
    data={
        'commit': 'Sign in',
        'utf8': '',
        'authenticity_token': token,
        'login': 'Zhao-panpan',
        'password': 'xxxxx'
    },
    cookies = ret_cookie_dict
)

ret1_cookie_dict = ret1.cookies.get_dict()

###############  查看个人email设置页面   #########################

ret3 = requests.get(
    url='https://github.com/settings/emails',
    headers={
        'Host': 'github.com',
        'Origin': 'https://github.com',
        'Pragma': 'no-cache',
        'Referer': 'https://github.com/login',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36'
    },
    cookies = ret1_cookie_dict
)

print(ret3.text)
github代码示例

相关文章:

  • 2022-01-03
  • 2022-12-23
  • 2021-11-23
  • 2022-02-09
  • 2021-07-18
  • 2022-12-23
  • 2022-12-23
  • 2021-07-07
猜你喜欢
  • 2022-01-22
  • 2022-12-23
  • 2022-12-23
  • 2021-11-29
  • 2021-09-17
相关资源
相似解决方案