Python Selenium脚本无法运行问题求助
Fixing Your First Selenium Script
Hey Nate, let's work through the bugs in your first Selenium script—you're almost there, just a couple of small syntax issues are holding you back!
Let's break down the problems:
- Missing parentheses on the click method: When you write
driver.find_element_by_id('game').click, you're only referencing the click method instead of executing it. Add parentheses:.click()to actually trigger the click action. - Wrong method name for sending keys: In Python's Selenium bindings, the method to input text is
send_keys()(all lowercase with an underscore), notsendKeys()—that's Java syntax, which will throw an AttributeError in Python.
Here's your corrected code:
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time # Initialize the Chrome driver driver = webdriver.Chrome(executable_path="C:\\Users\\natem\\Downloads\\chromedriver_win32\\chromedriver.exe") # Navigate to the game page driver.get("https://multiplayer-swordio.sedated.repl.co/") time.sleep(2) # Fixed: Added parentheses to .click() driver.find_element_by_id('game').click() time.sleep(2) # Locate input field, interact with it name = driver.find_element_by_id('input-form') name.click() # Fixed: Changed sendKeys to send_keys name.send_keys("user") name.send_keys(Keys.ENTER) time.sleep(20) # Don't forget to close the driver when finished! driver.quit()
A quick extra tip: While time.sleep() works for testing, for more reliable scripts, consider using Selenium's explicit waits (with WebDriverWait and expected_conditions) to wait for elements to become interactable instead of relying on fixed sleep times.
内容的提问来源于stack exchange,提问作者Nate Millner
相关产品推荐
相关产品推荐

