Python Selenium Webscraping返回找不到元素

时间:2019-06-15 06:08:14

标签: python selenium-webdriver xpath css-selectors webdriverwait

我有以下网页,需要使用用户名和密码登录。

<div class="MuiFormControl-root MuiTextField-root MuiFormControl-marginNormal MuiFormControl-fullWidth"><label class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated MuiInputLabel-shrink MuiInputLabel-outlined Mui-required Mui-required" data-shrink="true">Username<span class="MuiFormLabel-asterisk MuiInputLabel-asterisk"> *</span></label><div class="MuiInputBase-root MuiOutlinedInput-root MuiInputBase-fullWidth MuiInputBase-formControl"><fieldset aria-hidden="true" class="jss298 MuiOutlinedInput-notchedOutline" style="padding-left: 8px;"><legend class="jss299" style="width: 70.25px;"><span>​</span></legend></fieldset><input aria-invalid="false" autocomplete="email username" class="MuiInputBase-input MuiOutlinedInput-input" required="" type="text" autocapitalize="none" value=""></div></div>"

我的代码如下

uname = driver.find_element_by_class_name('MuiFormControl-root MuiTextField-root MuiFormControl-marginNormal MuiFormControl-fullWidth')

但是,它返回以下错误:

NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".MuiFormControl-root MuiTextField-root MuiFormControl-marginNormal MuiFormControl-fullWidth"}
  (Session info: chrome=75.0.3770.9

请你能帮我吗?

1 个答案:

答案 0 :(得分:0)

要将字符序列发送到所需字段,您必须为element_to_be_clickable()引入 WebDriverWait ,并且可以使用以下两种解决方案之一:

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.MuiInputBase-root.MuiOutlinedInput-root.MuiInputBase-fullWidth.MuiInputBase-formControl input.MuiInputBase-input.MuiOutlinedInput-input[autocomplete='email username']"))).send_keys("bluemountains1979")
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='MuiInputBase-root MuiOutlinedInput-root MuiInputBase-fullWidth MuiInputBase-formControl']//input[@class='MuiInputBase-input MuiOutlinedInput-input' and @autocomplete='email username']"))).send_keys("bluemountains1979")
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC