首页 > 解决方案 > 尝试使用 Selenium 和 Python 定位元素时出现“提供的双精度值是非有限的”错误

问题描述

我正在尝试让 selenium 向下滚动到网站中的一个按钮,该按钮的文本为“试试看!” 按钮内。

我的问题是按钮周围没有唯一的 ID 元素,我可以将视图滚动到该元素。此外,当我使用开发工具检查网站并从文本“试试看!”中搜索时 在 HTML 中我得到 72 个结果。我发现我需要第 18 个按钮,但我无法让浏览器滚动到该按钮。相反,我收到一条错误消息,提示“提供的双精度值是非有限的”。

您能否查看下面的代码并解释为什么我的浏览器没有向下滚动到按钮?

from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
import pathlib

# Get path to chromedriver
file_path = pathlib.Path(__file__).parent.absolute()
chromedriver_path = str(file_path)+"\\chromedriver.exe"

class Scraper:
    def __init__(self):
        
        # Open website
        self.driver = webdriver.Chrome(chromedriver_path)
        print(self.driver)
        self.driver.get(
            "https://flespi.io/gw/#/tags/!/devices/get_devices_dev_selector_messages")
        sleep(5)
        
        # Get the 18th button that says 'Try it out!'. Position()=17 because starts with 0.
        element = self.driver.find_element_by_xpath(
            '(//input[@value="Try it out!"])[position()=17]')
        
        # Scroll to the button and click it
        actions = ActionChains(self.driver)
        actions.move_to_element(element).perform()
        element.click()

        sleep(5)

Scraper()

标签: pythonseleniumxpathcss-selectorswebdriverwait

解决方案


要获取 Try it out 按钮并单击它,首先创建一个 webdriver 等待等待元素可单击。

element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='devices_get_devices_dev_selector_messages_content']/form/div[3]/input")))
element.click()

进口

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC

推荐阅读