JavascriptException : Message: javascript error: arguments[0]. click is not a function error using arguments[0].click 通过 Selenium 和 Python

标签 javascript python selenium selenium-webdriver webdriver

我一直在对一些网站进行网络抓取,以获取用于网络抓取练习的位置。这段代码让我了解酒店品牌的各个城市级别,但每当我在我的代码中使用 driver.execute_script("arguments[0].click();", button) 时(如倒数第二行所示)我得到这个错误:

JavascriptException: Message: javascript error: arguments[0].click is not a function

下面是我迄今为止编写的代码示例。

for state in state_links:
driver = Chrome(path_to_chrome_driver)
link = 'https://www.ihg.com/destinations/us/en/united-states/' + state.lower().replace(' ', '-')
driver.get(link)
city_links = driver.find_elements_by_xpath('//div[@class="countryListingContainer col-xs-12"]//ul//div//li//a//span')
city_links = [thing.text for thing in city_links]
driver.close()
for city in city_links:
    driver = Chrome(path_to_chrome_driver)
    link2 = 'https://www.ihg.com/destinations/us/en/united-states/' + state.lower().replace(' hotels', '').replace(' ', '-') + '/' + city.lower().replace(' ', '-')
    driver.get(link2)
    hotel_links = driver.find_elements_by_xpath('//div[@class="hotelList-detailsContainer"]//div//div//p//a')
    hotel_links = [elem.text for elem in hotel_links]
    driver.close()
    for hotel in hotel_links:
        driver = Chrome(path_to_chrome_driver)
        driver.get(link2)
        driver.implicitly_wait(15)
        driver.execute_script("arguments[0].click();", hotel)
        driver.implicitly_wait(10)

最佳答案

这个错误信息...

JavascriptException: Message: javascript error: arguments[0].click is not a function

...意味着使用 execute_script()arguments[0] 上调用 click() 失败。


有关这些步骤的更多信息将有助于我们构建规范的答案。但是,大概是在您收集 hotel_links 之后:

driver.get(link2)
hotel_links = driver.find_elements_by_xpath('//div[@class="hotelList-detailsContainer"]//div//div//p//a')

所以最初,hotel_links 包含 WebElements .但在下一行中,您将使用 elem.text 覆盖 List hotel_links,如下所示:

hotel_links = [elem.text for elem in hotel_links]

因此,hotel_links 现在包含 text 类型的元素。

由于 text 元素不支持 click(),因此当您尝试在文本元素上调用 click() 时继续前进通过 execute_script(),您会看到上述错误。


解决方案

如果您需要酒店链接的文本,请将它们存储在单独的列表中,如下所示:

hotel_links_text = [elem.text for elem in hotel_links]

引用

您可以在以下位置找到一些相关讨论:

关于JavascriptException : Message: javascript error: arguments[0]. click is not a function error using arguments[0].click 通过 Selenium 和 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62093844/

相关文章:

python - 有没有办法在没有文件名的情况下找到Python错误的根源?

javascript - Fancybox 关闭现有弹出窗口

javascript - 在引用 ScrollView 上 react native 错误,但工作

javascript - 查找最后一次匹配出现的索引

python - ffmpeg的子进程调用返回负值

python - 即使在 django 的 settings.py 中提供正确的设置后,数据库连接也无法工作

selenium - 如何使用机器人框架和 selenium 读取 Web 控制台输出?

javascript - 'this' 没有选择 jquery 函数

python - 将项目列表转换为项目元组列表

javascript - 界面测试工具