首页 > 代码库 > selenium2 python范例

selenium2 python范例

selenium2 python范例

下面脚本的功能是:打开谷歌浏览器--》跳转到某个网址--》输入用户名和密码登录--》读取页面内的数据并求和。

 1 # coding=utf-8 #编码声明
 2 import time
 3 from selenium import webdriver
 4 
 5 # 跳转到首页
 6 driver = webdriver.Chrome()  # Optional argument, if not specified will search path.
 7 driver.implicitly_wait(15)
 8 driver.get(http://xxx.xxx.xxx)  # 网址
 9 # driver.maximize_window()
10 time.sleep(5)  # Let the user actually see something!
11 loginButton1 = driver.find_element_by_id(login)  # 通过id定位元素
12 loginButton1.click()
13 driver.find_element_by_id(username).send_keys(‘xxxxxx)  # 用户名
14 driver.find_element_by_id(password).send_keys(yyyyyy)  # 密码
15 time.sleep(5)
16 driver.find_element_by_xpath(//button[@type="submit"]).click() # 通过xpath定位元素
17 time.sleep(5)  # Let the user actually see something!
18 
19 # 设置机构
20 driver.find_element_by_xpath("//*[@id=‘profile-messages‘]/a/b").click()
21 driver.find_element_by_xpath("//*[@id=‘profile-messages‘]/ul/li[3]/a").click()
22 time.sleep(5)
23 # 作品排行
24 driver.find_element_by_xpath("//*[@id=‘articles_Rank‘]/a").click()
25 # 全部媒体
26 driver.find_element_by_xpath("//*[@id=‘media_0‘]").click()
27 # 设置时间
28 driver.find_element_by_xpath("//*[@id=‘reservation‘]").click()
29 driver.find_element_by_xpath("//div[@class=‘calendar left‘]//th[@class=‘prev available‘]").click()
30 driver.find_element_by_xpath("//div[@class=‘calendar left‘]//td[@data-title=‘r0c6‘]").click()  # 10月1号
31 driver.find_element_by_xpath("//div[@class=‘calendar right‘]//th[@class=‘prev available‘]").click()
32 driver.find_element_by_xpath("//div[@class=‘calendar right‘]//td[@data-title=‘r5c1‘]").click()  # 10月31号
33 driver.find_element_by_xpath("//body/div[8]/div[1]/div/button[1]").click()
34 
35 # 读取目标并求值
36 time.sleep(1)  # 加入延时,解决“click操作后立刻查找的元素使用element.text,报stale element错误”的问题
37 total = int(0)
38 elementList = driver.find_elements_by_xpath("//*[@id=‘articleContent‘]//td[5]")
39 for element in elementList:
40     text2 = element.text
41     value =http://www.mamicode.com/ int(text2)
42     total = total + value
43 hasNext = False
44 while 1:
45     buttonList = driver.find_elements_by_xpath("//*[@id=‘page‘]//a")
46     pageButton = buttonList[len(buttonList)-1]
47     if pageButton.text == "Next":
48         hasNext = True
49         driver.execute_script("arguments[0].scrollIntoView();", pageButton)  # 执行js语句,通过滚动页面,将不在视野内的元素挪到视野内。
50         pageButton.click()
51     else:
52         hasNext = False
53         driver.quit()
54         break
55     if hasNext:
56         time.sleep(1)
57         elementList = driver.find_elements_by_xpath("//*[@id=‘articleContent‘]//td[5]")
58         for element in elementList:
59             text1 = element.text
60             value =http://www.mamicode.com/ int(text1)
61             total = total + value
62             print "value: " + str(value)
63             print "total: " + str(total)
64 
65 
66 #
67 driver.quit()

 

selenium2 python范例