找到更改类名的div(selenium)

时间:2016-10-22 18:42:45

标签: python python-2.7 selenium automation

我正在网上参加硒课程,我们正在自动化登录。讲座已经过时,我们正在使用的网站已经更新(Quora)。

问题是,输入字段有随机生成的类名,这使得“ find_element_by_id 方法毫无用处。

我无法弄清楚如何登录不同的会话。 如何在不同的会话期间选择这些字段(具有不同的类名)。这就是我的代码。先感谢您。我试过问课程讲师,但他整周没有回复。

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys


driver = webdriver.Chrome(executable_path = r'/Users/mpbro17/Desktop/chromedriver')

driver.get('https://www.quora.com')

driver.find_element_by_id("__w2_fy0VXDC_email").clear()
driver.find_element_by_id("__w2_fy0VXDC_email").send_keys("programmingdude183@gmail.com")
driver.find_element_by_id("__w2_fy0VXDC_password").clear()
driver.find_element_by_id("__w2_fy0VXDC_password").send_keys("testpassword1")
driver.find_element_by_id("__w2_fy0VXDC_submit_button").click()

错误

Traceback (most recent call last):
  File "/Users/mbpro/Desktop/projects/scraping_course/test_quora_login.py", line 13, in <module>
    driver.find_element_by_name("email").clear()
  File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 92, in clear
    self._execute(Command.CLEAR_ELEMENT)
  File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 494, in _execute
    return self._parent.execute(command, params)
  File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidElementStateException: Message: invalid element state: Element is not currently interactable and may not be manipulated
  (Session info: chrome=53.0.2785.143)
  (Driver info: chromedriver=2.24.417412 (ac882d3ce7c0d99292439bf3405780058fcca0a6),platform=Mac OS X 10.11.5 x86_64)

3 个答案:

答案 0 :(得分:0)

请尝试使用css选择器:

driver.find_element_by_css_selector('[id$="email"]')
driver.find_element_by_css_selector('[id$="password"]')
driver.find_element_by_css_selector('[id$="submit_button"]')

答案 1 :(得分:0)

您可以使用find_element_by_name方法查找您的元素(电子邮件和密码)和cssSelector for Login按钮。我想,这不会让你心灰意冷。

driver.find_element_by_name("email").clear()
driver.find_element_by_name("email").send_keys("programmingdude183@gmail.com")
driver.find_element_by_name("password").clear()
driver.find_element_by_name("password").send_keys("testpassword1")
driver.find_element_by_css_selector("input[value='Login']").click()

答案 2 :(得分:0)

你必须使用名称作为标准。但是如果你按名称属性去,则存在两个元素。

enter image description here

请按以下xpath

进行操作
//div[@class='regular_login']//input[@name='email']
//div[@class='regular_login']//input[@name='password']
//div[@class='regular_login']//input[contains(@class,'submit')]