Python3 爬虫带上 cookie


当前第2页 返回上一页

Code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

#!/usr/bin/env python

# -*- coding: utf-8 -*-

"""

__author__ = 'pi'

__email__ = 'pipisorry@126.com'

 

"""

import urllib.request, urllib.parse, urllib.error

import http.cookiejar

 

LOGIN_URL = 'http://acm.hit.edu.cn/hoj/system/login'

values = {'user': '******', 'password': '******'} # , 'submit' : 'Login'

postdata = urllib.parse.urlencode(values).encode()

user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'

headers = {'User-Agent': user_agent, 'Connection': 'keep-alive'}

 

cookie_filename = 'cookie.txt'

cookie = http.cookiejar.MozillaCookieJar(cookie_filename)

handler = urllib.request.HTTPCookieProcessor(cookie)

opener = urllib.request.build_opener(handler)

 

request = urllib.request.Request(LOGIN_URL, postdata, headers)

try:

  response = opener.open(request)

  page = response.read().decode()

  # print(page)

except urllib.error.URLError as e:

  print(e.code, ':', e.reason)

 

cookie.save(ignore_discard=True, ignore_expires=True) # 保存cookie到cookie.txt中

print(cookie)

for item in cookie:

  print('Name = ' + item.name)

  print('Value = ' + item.value)

 

get_url = 'http://acm.hit.edu.cn/hoj/problem/solution/?problem=1' # 利用cookie请求訪问还有一个网址

get_request = urllib.request.Request(get_url, headers=headers)

get_response = opener.open(get_request)

print(get_response.read().decode())

# print('You have not solved this problem' in get_response.read().decode())

推荐教程:《Python教程》

以上就是Python3 爬虫带上 cookie的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

django框架入门使用1.0

Python语言及其特点简介

Python如何计算时间差

Python安装包怎么下载

pandas妙招之 在dataframe中通过索引高效获取数据

Python二进制怎么转十进制?

Python开发的网站有哪些

Python列表怎么比较大小

Python pow函数怎么用

Python实现的凯撒密码算法示例

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...