一、页面分析
csdn登录页面如下图
二、引入selenium模块及驱动
2.1 并将安装好的chromedriver.exe引入到代码中
1
2
3
4
5
6
7
8
|
# -*- coding:utf-8 -*-
from selenium import webdriver
import os
import time
#引入chromedriver.exe
chromedriver = "c:/users/lex/appdata/local/google/chrome/application/chromedriver.exe"
os.environ[ "webdriver.chrome.driver" ] = chromedriver
browser = webdriver.chrome(chromedriver)
|
2.2 浏览器驱动引入
将驱动下载后,复制chromedriver.exe 到谷歌浏览器的安装路径下,与chrome.exe启动文件并列的目录下:
三、爬虫模拟登录
3.1 设置网址链接
1
2
3
|
#设置浏览器需要打开的url
url = "https://passport.csdn.net/login?code=public"
browser.get(url)
|
3.2 切换到账号密码登录
使用selenium模拟点击 账号密码登录的选项
1
2
|
#使用selenium选择 账号登录按钮
browser.find_element_by_link_text( "账号密码登录" ).click()
|
3.3 找到用户名密码的控件id
3.4 注入用户名和密码
根据页面代码分析,获得用户名的id属性为all,密码的id属性为password-number
使用python代码,注入用户名密码
1
2
3
4
5
|
browser.find_element_by_id( "all" ).clear()
browser.find_element_by_id( "all" ).send_keys( "xxxx@gmail.com" )
time.sleep( 2 )
browser.find_element_by_id( "password-number" ).clear()
browser.find_element_by_id( "password-number" ).send_keys( "1212121212" )
|
3.5 模拟登录点击
分析页面结构,模拟点击登录按钮。
分析可获得,登录按钮的class属性为btn btn-primary,根据class来锁定该按钮
1
2
3
|
time.sleep( 1 )
#增加一秒钟的时间间隔
browser.find_element_by_css_selector( "[class='btn btn-primary']" ).click()
|
四、成功登录csdn
五、完整代码
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
|
# -*- coding:utf-8 -*-
import os
import time
from selenium import webdriver # 从selenium导入webdriver
from selenium.webdriver.common.by import by
from selenium.webdriver.support.ui import webdriverwait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.chrome.options import options
import json
import time
#引入chromedriver.exe
chromedriver = "c:/users/lex/appdata/local/google/chrome/application/chromedriver.exe"
os.environ[ "webdriver.chrome.driver" ] = chromedriver
browser = webdriver.chrome(chromedriver)
#设置浏览器需要打开的url
url = "https://passport.csdn.net/login?code=public"
browser.get(url)
browser.find_element_by_link_text( "账号密码登录" ).click()
browser.find_element_by_id( "all" ).clear()
browser.find_element_by_id( "all" ).send_keys( "你的邮箱地址" )
time.sleep( 1 )
browser.find_element_by_id( "password-number" ).clear()
browser.find_element_by_id( "password-number" ).send_keys( "你的登录密码" )
time.sleep( 1 )
browser.find_element_by_css_selector( "[class='btn btn-primary']" ).click()
|
到此这篇关于python爬虫之利用selenium模块自动登录csdn的文章就介绍到这了,更多相关python自动登录csdn内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/weixin_42350212/article/details/115898831