第五章感觉是第四章的练习项目,无非就是多了一个模拟登录。

不分小节记录了,直接上知识点,可能比较乱。

1.常见的httpcode:

第5章 scrapy爬取知名问答网站

2.怎么找post参数?

先找到登录的页面,打开firebug,输入错误的账号和密码,观察post_url变换,从而确定参数。

3.读取本地的文件,生成cookies。

1 try:
2     import cookielib #py2
3 except:
4     import http.cookiejar as cookielib #py3

4.用requests登录知乎

 1 # -*- coding: utf-8 -*-
 2 __author__ = 'jinxiao'
 3 
 4 import requests
 5 try:
 6     import cookielib
 7 except:
 8     import http.cookiejar as cookielib
 9 
10 import re
11 
12 session = requests.session()  #实例化session,下面的requests可以直接换成session
13 session.cookies = cookielib.LWPCookieJar(filename="cookies.txt") #实例化cookies,保存cookies
14 #读取cookies
15 try:
16     session.cookies.load(ignore_discard=True)
17 except:
18     print ("cookie未能加载")
19 
20 #知乎一定要加上浏览器的头,其他网站不一定,一般都是要的
21 agent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0"
22 header = {
23     "HOST":"www.zhihu.com",
24     "Referer": "https://www.zhizhu.com",
25     'User-Agent': agent
26 }
27 
28 def is_login():
29     #通过个人中心页面返回状态码来判断是否为登录状态
30     inbox_url = "https://www.zhihu.com/question/56250357/answer/148534773"
31     response = session.get(inbox_url, headers=header, allow_redirects=False)  #禁止重定向,判断为是否登录
32     if response.status_code  != 200:
33         return False
34     else:
35         return True
36 
37 def get_xsrf():
38     #获取xsrf code
39     response = session.get("https://www.zhihu.com", headers=header)
40     match_obj = re.match('.*name="_xsrf" value="(.*?)"', response.text)
41     if match_obj:
42         return (match_obj.group(1))
43     else:
44         return ""
45 
46 
47 def get_index():
48     response = session.get("https://www.zhihu.com", headers=header)
49     with open("index_page.html", "wb") as f:
50         f.write(response.text.encode("utf-8"))
51     print ("ok")
52 
53 def zhihu_login(account, password):
54     #知乎登录
55     if re.match("^1\d{10}",account):
56         print ("手机号码登录")
57         post_url = "https://www.zhihu.com/login/phone_num"
58         post_data = {
59             "_xsrf": get_xsrf(),
60             "phone_num": account,
61             "password": password
62         }
63     else:
64         if "@" in account:
65             #判断用户名是否为邮箱
66             print("邮箱方式登录")
67             post_url = "https://www.zhihu.com/login/email"
68             post_data = {
69                 "_xsrf": get_xsrf(),
70                 "email": account,
71                 "password": password
72             }
73 
74     response_text = session.post(post_url, data=post_data, headers=header)
75     session.cookies.save()
76 
77 zhihu_login("18782902568", "admin123")
78 # get_index()
79 print(is_login())
zhihu_requests_login

相关文章:

  • 2021-12-08
  • 2022-12-23
  • 2021-10-30
  • 2021-07-08
  • 2022-12-23
  • 2022-12-23
  • 2021-04-07
  • 2021-08-20
猜你喜欢
  • 2021-12-22
  • 2021-07-22
  • 2021-07-28
  • 2021-05-02
  • 2021-11-15
  • 2021-06-26
  • 2022-12-23
相关资源
相似解决方案