使用Selenium的浏览器自动化,让我们看看它是如何进行的:
1.打开浏览器
2.创建浏览器实例并使用.get函数连接网站。
3.找到元素,这可以是找到输入框或按钮的任何东西,并使用selenium函数,如click(),send_keys()等与元素交互。
4.关闭浏览器
代码:
from selenium import webdriver
# For using sleep function because selenium
# works only when the all the elemets of the
# page is loaded.
import time
from selenium.webdriver.common.keys import Keys
# Creating an instance webdriver
browser = webdriver.Firefox()
browser.get('https://www.twitter.com')
# Let's the user see and also load the element
time.sleep(2)
login = browser.find_elements_by_xpath('//*[@id="doc"]/div[1]/div/div[1]/div[2]/a[3]')
# using the click function which is similar to a click in mouse.
login[0].click()
print("Loggin in Twitter")
user = browser.find_elements_by_xpath('//*[@id="login-dialog-dialog"]/div[2]/div[2]/div[2]/form/div[1]/input')
# Enter User Name
user[0].send_keys('USER-NAME')
user = browser.find_element_by_xpath('//*[@id="login-dialog-dialog"]/div[2]/div[2]/div[2]/form/div[2]/input')
# Reads password from a text file because
# saving the password in a script is just silly.
with open('test.txt', 'r') as myfile:
Password = myfile.read().replace('\n', '')
user.send_keys(Password)
LOG = browser.find_elements_by_xpath('//*[@id="login-dialog-dialog"]/div[2]/div[2]/div[2]/form/input[1]')
LOG[0].click()
print("Login Sucessfull")
time.sleep(5)
elem = browser.find_element_by_name("q")
elem.click()
elem.clear()
elem.send_keys("Geeks for geeks ")
# using keys to send special KEYS
elem.send_keys(Keys.RETURN)
print("Search Sucessfull")
# closing the browser
browser.close()








暂无数据