ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

python:Selenium 4.47 编码新的写法

python:Selenium 4.47 编码新的写法 pip install seleniumpip show seleniumName: seleniumVersion: 4.47.0Summary: Official Python bindings for Selenium WebDriverHome-page: https://www.selenium.devSelenium报错‘WebDriver’ object has no attribute ‘find_element_by_id’原因Selenium4.3.0及以上版本已经彻底移除了find_element_by_id()、find_element_by_xpath()、find_element_by_class_name()这一类by_*的方法。旧写法已经废弃不再支持。❌ 旧写法会报错# 已经废弃driver.find_element_by_id(username)driver.find_element_by_xpath(//div)driver.find_element_by_class_name(box)driver.find_elements_by_id(xxx)✅ 新写法统一使用find_element配合By类需要导入from selenium.webdriver.common.by import Byfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy driverwebdriver.Chrome()# 通过id查找elemdriver.find_element(By.ID,username)# xpathelemdriver.find_element(By.XPATH,//div[classitem])# class nameelemdriver.find_element(By.CLASS_NAME,box)# css选择器elemdriver.find_element(By.CSS_SELECTOR,.content)# name属性elemdriver.find_element(By.NAME,password)# 查找多个元素 find_elements (带s)elemsdriver.find_elements(By.CLASS_NAME,list-item)By类支持的定位方式定位方式写法idBy.IDxpathBy.XPATHclassBy.CLASS_NAMEcss选择器By.CSS_SELECTORname属性By.NAME标签名tagBy.TAG_NAME链接文本By.LINK_TEXT部分链接文本By.PARTIAL_LINK_TEXT常见坑忘记导入By直接写driver.find_element(id,xxx)也可以不推荐可读性差# 也能运行但建议用By常量driver.find_element(id,username)网上很多老教程还是旧API复制过来直接报错。如果你的代码大量是旧方法不想全部改可以降级selenium版本不推荐pipinstallselenium4.2.0建议改成新标准写法新版本有更好的等待、调试能力。完整示例fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy driverwebdriver.Chrome()driver.get(https://example.com)# 定位id为search的输入框search_inputdriver.find_element(By.ID,search)search_input.send_keys(selenium)driver.quit()
返回列表