Reputation: 1
I'm a beginner in learning python and have a problem with my code. It seems like a simple error but I cannot find a solution for this error.
Here's a code
import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.google.co.jp/")
WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.NAME, "q"))
search_box = driver.find_element_by_name('q')
search_box.send_keys('Selenium')
File "<ipython-input-12-1cac2821f197>", line 4
search_box = driver.find_element_by_name("q")
^
SyntaxError: invalid syntax
search_box.submit()
driver.implicitly_wait(10)
driver.find_element_by_link_text("Selenium - Web Browser Automation").click()
time.sleep(5)
driver.quit()
The problem is on line 6. I tried to run the code, but it says "search_box" is invalid syntax. Does anyone know the solution for this?
Upvotes: 0
Views: 1635
Reputation: 193098
You need to consider a couple of things as follows:
Once you induce WebDriverWait you don't have to use find_element_by_*
again. So you can remove the line:
search_box = driver.find_element_by_name('q')
As you intent to interact with the element instead of presence_of_element_located()
you need the expected_conditions of element_to_be_clickable()
.
Moreover, element_to_be_clickable()
should be called within a tuple
as it is not a function but a class, where the initializer expects just 1 argument beyond the implicit self:
class element_to_be_clickable(object):
""" An Expectation for checking an element is visible and enabled such that you can click it."""
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
element = visibility_of_element_located(self.locator)(driver)
if element and element.is_enabled():
return element
else:
return False
You can find a relevant discussion in init() takes 2 positional arguments but 3 were given using WebDriverWait and expected_conditions as element_to_be_clickable with Selenium Python
You can club up the required three(3) lines into a single line as follows:
WebDriverWait(driver, 10).until((EC.element_to_be_clickable(By.NAME, "q"))).send_keys('Selenium')
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
Upvotes: 0
Reputation: 1
In this line:
WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.NAME, "q"))
there is an closing bracket in the end missing. And WebDriverWait isn't imported yet:
from selenium.webdriver.support.ui import WebDriverWait
Upvotes: 0
Reputation: 77347
Syntax errors are frequently on the lines above, especially when those lines include parenthesis. A trick is to count opening and closing parens. If the result isn't zero, you've got a problem:
WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.NAME, "q"))
^ ^ ^ ^^ ^^
1 0 1 23 21
Upvotes: 1