简体   繁体   中英

Python Selenium WebElement element - invalid syntax

I'm trying to scroll to a particular element on a page but before I do that I'm trying to set myelement to be a WebElement object, heres the code:

from selenium import webdriver

browser.get("http://www.agoda.com/the-coast-resort-koh-phangan/hotel/koh-phangan-th.html")
WebElement myelement = browser.findElement(By.id("next-page"));

But it comes back with the error:

WebElement myelement = browser.findElement(By.id("next-page"));
                   ^
SyntaxError: invalid syntax

What am I missing?

Update: Ok looks like I was trying to write Java! as the first reply has stated, but then my question kind of changes since my actual code is:

from selenium import webdriver
from selenium.webdriver.common.by import By

browser = webdriver.Firefox()
browser.get("http://www.agoda.com/the-coast-resort-koh-phangan/hotel/koh-phangan-th.html")

browser.find_element_by_xpath("//a[@id='next-page']").click()

myelement = browser.find_element(By.id("next-page"));
((JavascriptExecutor) browser).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);

browser.find_element_by_xpath("//a[@id='next-page']").click()

Which gives the error:

File "<ipython-input-22-bb983f3ceca8>", line 10
    ((JavascriptExecutor) browser).executeScript("arguments[0].scrollIntoView(true);", element);
                            ^
SyntaxError: invalid syntax

Probably writing Java again, but how should this be amended?

Python isn't Java. (WebElement element = ...;)

Here's a link to the documentation for the python methods etc.

What you actually want is:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://www.agoda.com/the-coast-resort-koh-phangan/hotel/koh-phangan-th.html")
myelement = browser.find_element_by_id("next-page")

Although you can use By in the above but find_element_by_id is a bit more readable imo.

Edit:

Likewise for the second bit

browser.execute_script("arguments[0].scrollIntoView();", element)

I haven't used the above in awhile, so it may actually be the following I don't recall atm:

browser.execute_script("return arguments[0].scrollIntoView();", element)

You can also scroll to an element like this:

browser.execute_script("window.scrollTo(0, %d)" % element.location['y'])

Thread.sleep(500); also isn't going to work, and you can remove the semicolons ; after your lines, they're not necessarily "wrong" but they are redundant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM