解决:python爬虫运行报错——AttributeError: ‘WebDriver‘ object has no attribute ‘find_elements_by_class_name‘

2022/07/07
距离上次使用selenium14天,发现莫名报错。

1.发现selenium里查找元素的方法使用报错

解决:python爬虫运行报错——AttributeError: ‘WebDriver‘ object has no attribute ‘find_elements_by_class_name‘_第1张图片

2.查看find_elements的源码(发现是源码改了):

解决:python爬虫运行报错——AttributeError: ‘WebDriver‘ object has no attribute ‘find_elements_by_class_name‘_第2张图片
所以应该由原来的这种形式
在这里插入图片描述

变换为
在这里插入图片描述

buttons = driver.find_element(by=By.CLASS_NAME,value="Button ContentItem-action Button--plain Button--withIcon Button--withLabel")

记得还要在引入库包那里加上这一句:
在这里插入图片描述

from selenium.webdriver.common.by import By

其他的几种查找元素的方法以此类推

关于此部分源码如下:

    def find_element(self, by=By.ID, value=None) -> WebElement:
        """
        Find an element given a By strategy and locator.

        :Usage:
            ::

                element = driver.find_element(By.ID, 'foo')

        :rtype: WebElement
        """
        if isinstance(by, RelativeBy):
            elements = self.find_elements(by=by, value=value)
            if not elements:
                raise NoSuchElementException(f"Cannot locate relative element with: {by.root}")
            return elements[0]

        if by == By.ID:
            by = By.CSS_SELECTOR
            value = '[id="%s"]' % value
        elif by == By.CLASS_NAME:
            by = By.CSS_SELECTOR
            value = ".%s" % value
        elif by == By.NAME:
            by = By.CSS_SELECTOR
            value = '[name="%s"]' % value

        return self.execute(Command.FIND_ELEMENT, {
            'using': by,
            'value': value})['value']

    def find_elements(self, by=By.ID, value=None) -> List[WebElement]:
        """
        Find elements given a By strategy and locator.

        :Usage:
            ::

                elements = driver.find_elements(By.CLASS_NAME, 'foo')

        :rtype: list of WebElement
        """
        if isinstance(by, RelativeBy):
            _pkg = '.'.join(__name__.split('.')[:-1])
            raw_function = pkgutil.get_data(_pkg, 'findElements.js').decode('utf8')
            find_element_js = f"return ({raw_function}).apply(null, arguments);"
            return self.execute_script(find_element_js, by.to_dict())

        if by == By.ID:
            by = By.CSS_SELECTOR
            value = '[id="%s"]' % value
        elif by == By.CLASS_NAME:
            by = By.CSS_SELECTOR
            value = ".%s" % value
        elif by == By.NAME:
            by = By.CSS_SELECTOR
            value = '[name="%s"]' % value

        # Return empty list if driver returns null
        # See https://github.com/SeleniumHQ/selenium/issues/4555
        return self.execute(Command.FIND_ELEMENTS, {
            'using': by,
            'value': value})['value'] or []

    @property

你可能感兴趣的:(python,爬虫,python,开发语言)