我正在尝试制作一个基于 Python 和 InstaPy 的 BOT,它可以登录 Instagram、点赞帖子并发表评论。请帮忙调试以下代码。
代码是:
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
browser = webdriver.Firefox()
browser.implicitly_wait(5)
browser.get('https://www.instagram.com/')
login_link = browser.find_element(By.XPATH, "//a[text()='Log in']")
login_link.click()
sleep(5)
browser.close()
错误消息是:
File "C:\0. D drive\BOT\step2.py", line 10, in login_link = browser.find_element(By.XPATH, "//a[text()='Log in']") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\nadel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\selenium\webdriver\remote\webdriver.py", line 831, in find_element return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\nadel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\selenium\webdriver\remote\webdriver.py", line 440, in execute self.error_handler.check_response(response) File "C:\Users\nadel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\selenium\webdriver\remote\errorhandler.py", line 245, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //a[text()='Log in'] Stacktrace: RemoteError@chrome://remote/content/shared/RemoteError.sys.mjs:8:8 WebDriverError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:191:5 NoSuchElementError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:509:5 dom.find/</<@chrome://remote/content/shared/DOM.sys.mjs:136:16
这段代码就可以解决问题:
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
browser = webdriver.Firefox()
browser.implicitly_wait(5)
browser.get('https://www.instagram.com/')
login_link = browser.find_element(By.XPATH, '//*[@id="loginForm"]/div/div[3]/button')
action = ActionChains(browser)
action.click(login_link).perform()
sleep(5)
browser.close()