gpt4 book ai didi

Python Selenium WebElement 元素 - 语法无效

转载 作者:行者123 更新时间:2023-11-28 21:46:43 25 4
gpt4 key购买 nike

我试图滚动到页面上的特定元素,但在我这样做之前,我试图将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com