我正在尝试滚动到页面上的特定元素,但在此之前我尝试将 myelement 设置为 WebElement 对象,代码如下:
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"));
但是返回错误:
WebElement myelement = browser.findElement(By.id("next-page"));
^
SyntaxError: invalid syntax
我错过了什么?
更新:好吧,看起来我正在尝试编写 Java!正如第一个答复所述,但后来我的问题发生了变化,因为我的实际代码是:
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()
这给出了错误:
File "<ipython-input-22-bb983f3ceca8>", line 10
((JavascriptExecutor) browser).executeScript("arguments[0].scrollIntoView(true);", element);
^
SyntaxError: invalid syntax
可能又要写Java了,但是这个应该怎么修改呢?
最佳答案
Python 不是 Java。 (WebElement 元素 = ...;)
这里是 documentation 的链接对于 python 方法等。
你真正想要的是:
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")
尽管您可以在上面使用 By
,但在我看来,find_element_by_id
更具可读性。
编辑:
第二位也是如此
browser.execute_script("arguments[0].scrollIntoView();", element)
我已经有一段时间没有使用上面的内容了,所以实际上可能是以下我不记得的 atm:
browser.execute_script("return arguments[0].scrollIntoView();", element)
您还可以滚动到这样的元素:
browser.execute_script("window.scrollTo(0, %d)" % element.location['y'])
Thread.sleep(500);
也不起作用,您可以删除行后的分号 ;
,它们不一定是“错误的” “但它们是多余的。
关于Python Selenium WebElement 元素 - 无效语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37515755/