新selenium模拟登录知乎

关于参数请求错误1001

  • 由于知乎的反爬机制可以检测到selenium脚本运行被拒绝访问1001
  • 在chrome浏览器中的windows.navigator.webdriver结果为Ture,而正常使用浏览器的时候该值为False
  • 只需将设置其为开发者模式,防止被各大网站识别出来使用了Selenium
#设置为开发者模式
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-automation'])
b=webdriver.Chrome(executable_path='C:\\Desktop\\chromedriver.exe',options=options)

步骤

  1. 获取链接
  2. 根据Xpath或者css获取位置
  3. 输入参数
  4. 点击登录

代码

from selenium import webdriver
from scrapy.selector import Selector

# 进入开发者模式
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-automation'])
b=webdriver.Chrome(executable_path='C:\\Users\\23607\\Desktop\\py\\chromedriver.exe',options=options)

b.get('https://www.zhihu.com/signin?next=%2F')
#切换到密码登录
b.find_element_by_xpath('//*[@id="root"]/div/main/div/div/div[2]/div/form/div[1]/div[2]').click()

#根据css获取位置并输入账号密码
b.find_element_by_css_selector('.SignFlow-accountInputContainer div input[name="username"]').send_keys('账号')
b.find_element_by_css_selector('.SignFlow-password div div input[name="password"]').send_keys('密码')
#根据xpath获取相应位置并点击登录
b.find_element_by_xpath('//*[@id="root"]/div/main/div/div/div[2]/div/form/button').click()

 b.quit()
发布了9 篇原创文章 · 获赞 9 · 访问量 2951

猜你喜欢

转载自blog.csdn.net/Rice__/article/details/99699660