我想使用Python Selenium登录此web site,我已编写此代码:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
class Mps(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.google.it/"
self.verificationErrors = []
self.accept_next_alert = True
def test_mps(self):
driver = self.driver
driver.get(self.base_url + "/portaleTitolari/titolari.html")
driver.find_element_by_id("ext-gen30").clear()
driver.find_element_by_id("ext-gen30").send_keys("username33")
driver.find_element_by_id("ext-gen11").clear()
driver.find_element_by_id("ext-gen11").send_keys("password33")
driver.find_element_by_id("ext-gen38").click()
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException as e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
问题是用户名和密码输入字段名称每次都会更改。在这种情况下,如何找到用户名,密码输入字段和登录按钮?
答案 0 :(得分:0)
这两个输入字段似乎都有静态类。只需使用xpath搜索具有给定类的输入元素。类似的东西:
driver.find_element_by_xpath("//input[@class='login_component_input']")
由于密码使用相同的类,您可以尝试在查询中包含元素类型:
driver.find_element_by_xpath("//input[@class='login_component_input' and @type='password']")
xpath是一种非常富有表现力的语言。如果你要自动化网站,你应该花一些时间来理解它。