最新!python模拟登陆知乎

想爬一些知乎的数据,但过程并不顺利,这几天看了网上很多大神的帖子,最近的也是18年8月的。目前知乎改版,网上现有的方法全部都不能登陆了,会报参数异常的错误。

捣鼓了好久,曲线救国,2种方法

一、selenium

用selenium模拟浏览器登陆,首先QQ要在电脑上登陆,python代码自动打开chrome浏览器,选择以QQ登陆的方式登陆知乎,这里需要人工点一次登陆才行。真的是曲线救国。。。。。。。

代码如下:

import time

from selenium import webdriver

# sys.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
wd = webdriver.Chrome('C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe')
# 打开知乎首页
wd.get('https://www.zhihu.com/')
# 进入登陆页面
wd.find_element_by_xpath(".//*[@class='SignContainer-switch']/span").click()
# 点击社交网络账号登陆
wd.find_element_by_xpath(".//*[@class='Login-socialLogin']/button").click()  # 点击QQ登陆
wd.find_element_by_xpath(".//*[@class='Login-socialButtonGroup']/button[3]").click()  # 点击QQ登陆
time.sleep(10)  # 时间不够的自己加
wd.refresh()  # 一定要刷新

二、cookie

这个方法比上一个方法简单

自己先在网页上登陆一次知乎,然后把保存在本地的cookie复制下来

在python的请求头里加上你的cookie,大功告成,下次自动登陆

(务必把cookie的所有内容复制下来)

最新!python模拟登陆知乎

代码如下:

import requests

headers={
    'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
    'Referer':'https://www.zhihu.com/',
    'Cookie':'xxxxxxxxxxxxxxxx'
}
res=requests.get("https://www.zhihu.com/search?type=content&q=python",headers=headers)
print(res.text)