Python extra: use selenium to automatically log in to CSDN

Hello, everyone, I am wangzirui32, today we will learn how to use selenium to automatically log in to CSDN.

1. Login page analysis

First, we open the login page and start the analysis:
log in pagewe have to click on the "account password login" to log in. Its HTML source code is:
Insert picture description here
Then, let's analyze the login user name box and password box: after the
Username HTML codePassword HTML source codeInsert picture description here
analysis is over, we start to write the code.

2. Start writing

Here I encapsulate the login code into a function so that other programs can call it (see the comments if you don't understand):

def csdn_login(driver, username, password):
	# 访问登录页面
    driver.get('https://passport.csdn.net/login?code=public')
    # 查询内容为“账号密码登录”的标签对象
    login_link = driver.find_element_by_link_text("账号密码登录")
    # 然后点击
    login_link.click()

	# 用户名框 查询id为all的标签
    login_username = driver.find_element_by_id("all")
    # 密码框 查询id为password-number的标签
    login_password = driver.find_element_by_id("password-number")

	# 输入用户名
    login_username.send_keys(username)
    # 输入密码
    login_password.send_keys(password)

	# 登录按钮 获取class为btn btn-primary的button标签
    button = driver.find_element_by_xpath("//button[@class='btn btn-primary']")
    # 点击按钮 登录成功
    button.click()

if __name__  == "__main__":
	# 开始测试
	from selenium.webdriver import Firefox
	# 把executable_path设置为你电脑内浏览器驱动的位置目录
	driver = Firefox(executable_path='geckodriver.exe')
	# 调用
	csdn_login(driver, "你的用户名", "你的密码")

Run the code, you can automatically log in to CSDN!


Today's course is here, if you are interested, you can bookmark it, and bye bye!

Guess you like

Origin blog.csdn.net/wangzirui32/article/details/113845588