Python+Selenium登录GitHub实例

1、话不多说,直接上代码

 1 from selenium import webdriver  # 导入包
 2 import time
 3 driver = webdriver.Chrome()    #  指定浏览器
 4 driver.get("https://github.com/login")  #  指定网址
 5 driver.implicitly_wait(10)  # 等待
 6 #  定位到登录框输入用户名和密码
 7 driver.maximize_window()
 8 driver.find_element_by_xpath("//*[@id='login_field']").send_keys("用户名")
 9 driver.find_element_by_id("password").send_keys("密码")
10 driver.find_element_by_xpath("//*[@value='Sign in']").click()
11 time.sleep(3)
12 #  点击右上角设置
13 driver.find_element_by_css_selector('summary[class="Header-link"] span:nth-child(3)').click()
14 #  driver.find_element_by_xpath("/html/body/div[1]/header/div[7]/details/summary").click()
15 time.sleep(1)
16 #  取值
17 t = driver.find_element_by_css_selector('a[role="menuitem"] strong').text
18 print("获取的账户名称是:{}".format(t))
19 if t == "用户名":
20     print("登录成功!")
21 else:
22     print("登录失败")
23 #  退出登录
24 #  driver.find_element_by_xpath("//form[@class='logout-form']/button").click()
25 driver.find_element_by_css_selector(".dropdown-item.dropdown-signout").click()
26 driver.quit()  #  退出

 2、增强代码可读性

 1 from selenium import webdriver
 2 import time
 3 def login(driver, username, password):
 4     '''登录github'''
 5     # 打开github首页
 6     driver.get("https://github.com/login")
 7     driver.implicitly_wait(10)
 8     driver.maximize_window()
 9     # 输入账号
10     driver.find_element_by_xpath("//*[@id='login_field']").send_keys(username)
11     # 输入密码
12     driver.find_element_by_id("password").send_keys(password)
13     driver.find_element_by_xpath("//*[@value='Sign in']").click()
14 def logout(driver):
15     '''退出github'''
16     time.sleep(3)
17     # 点右上角设置
18     # driver.find_element_by_css_selector('summary[class="Header-link"] span:nth-child(3)').click()
19     #driver.find_element_by_xpath("/html/body/div[1]/header/div[7]/details/summary").click()
20     #time.sleep(1)
21     # 点sign out
22     driver.find_element_by_css_selector(".dropdown-item.dropdown-signout").click()
23     #  driver.find_element_by_xpath("//form[@class='logout-form']/button").click()
24     driver.quit()
25 def check(driver):
26     # 登录成功后,获取我的账户名称
27     time.sleep(5)
28     # 点右上角设置
29     driver.find_element_by_xpath("/html/body/div[1]/header/div[7]/details/summary").click()
30     # driver.find_element_by_css_selector('summary[class="Header-link"] span:nth-child(3)').click()
31     # 获取账户名称
32     time.sleep(1)
33     t = driver.find_element_by_css_selector('a[role="menuitem"] strong').text
34     print("获取到我的账户名称:%s" % t)
35     if t == "用户名":
36         print("登录成功!")
37     else:
38         print("登录失败!")
39 if __name__ == "__main__":
40     driver = webdriver.Chrome()
41     # 调用登录
42     login(driver, "用户名", "密码")
43     # 检查是否登录成功
44     check(driver)
45     print("hello  jiale!")
46     # 调用退出
47     logout(driver)

 

  

posted on 2020-09-18 17:40  Tester十点半  阅读(480)  评论(0编辑  收藏  举报

导航