解决:python爬虫运行报错——AttributeError: ‘WebDriver‘ object has no attribute ‘find_elements_by_class_name‘
Posted ~晚风微凉~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决:python爬虫运行报错——AttributeError: ‘WebDriver‘ object has no attribute ‘find_elements_by_class_name‘相关的知识,希望对你有一定的参考价值。
2022/07/07
距离上次使用selenium14天,发现莫名报错。
1.发现selenium里查找元素的方法使用报错
2.查看find_elements的源码(发现是源码改了):
所以应该由原来的这种形式:
变换为:
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爬虫运行报错——AttributeError: ‘WebDriver‘ object has no attribute ‘find_elements_by_class_name‘的主要内容,如果未能解决你的问题,请参考以下文章
解决:python爬虫运行报错——AttributeError: ‘WebDriver‘ object has no attribute ‘find_elements_by_class_name‘
python 网络爬虫报错“UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position”解决方案(