当我尝试运行代码时,它首先运行得很好,但最后,链接没有被点击! 我也尝试了
.submit()
功能,但它也不起作用。
这是弹出的行:
driver.find_element_by_xpath('//*[@id="mount_0_0_3z"]/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/button[1]').click()
错误:
AttributeError: 'NoneType' object has no attribute 'click'
代码:
import time
from selenium import webdriver
from data import username, password
def login(username, password):
driver = webdriver.Chrome('chromedriver/chromedriver.exe')
driver.get('https://instagram.com')
time.sleep(2)
driver.find_element_by_xpath('//*[@id="mount_0_0_3z"]/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/button[1]').click()
time.sleep(2)
login(username, password)
您尝试过使用
WebDriverWait
吗?该元素可能在 DOM 中可见,但也可能需要可见。可见是什么意思?这意味着按钮不仅需要位于 DOM 中,而且需要具有大于 0 的高度和宽度。以下是您可以尝试的代码片段:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
def wait_for_element_clickable(driver, x_path, timeout):
"""Waits for an element to be visible and clickable, then clicks the element.
Visible means that the element is not only in the DOM but has
a width and height greater than 0.
Args:
x_path (str): The XPATH for the element.
timeout (int): The amount of time to wait for the element to be visible and clickable.
click (bool, optional): Click the element after it is available. Defaults to False.
"""
try:
element = WebDriverWait(driver, timeout).until(
EC.element_to_be_clickable((By.XPATH, x_path))
)
element.click()
print("Element has been clicked")
return True
except TimeoutException as te:
print(f"Element was not found: {te}")
return False
正如 @ekoret 已经提到的,可能是元素没有足够的时间来加载。
使用 Selenium 时,最好始终使用 WebDriverWait 功能。这是一个代码片段,您可以轻松地在所有脚本上实现:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Chrome() #This assumes the chromedriver is on the same folder as your script
wait = WebDriverWait(driver, 10)
# Now you can use the WebDriverWait everytime you search for an element
element = wait.until(EC.element_to_be_clickable((By.XPATH, your_xpath_here)))
element.click()
根据元素的性质,您可能需要使用其他方法而不是 element_to_be_clickable。一些示例包括存在元素定位、元素可见。
您可以查看[文档][1]以获取更多信息。
希望有帮助! [1]:https://selenium-python.readthedocs.io/waits.html