Selenium报WebElement无startsWith属性错误修复方案
问题背景
- 爬取目标:
https://www.ifep.ro/justice/lawyers/lawyerspanel.aspx页面下所有归属目标域名的律师相关链接 - 初始代码运行时抛出错误:
'WebElement' object has no attribute 'startsWith' - 报错截图:

错误根因
错误由两个问题共同导致:
- 方法调用对象错误:遍历得到的元素是Selenium的
WebElement页面对象,不是字符串,本身不存在字符串前缀判断方法,需要先取出元素的href属性值才能做字符串匹配 - 方法名语法错误:
startsWith是JavaScript语言的字符串前缀判断方法,Python中对应的方法为全小写的startswith(),驼峰命名的方法在Python字符串中不存在
修复后完整代码
import time from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from webdriver_manager.chrome import ChromeDriverManager options = webdriver.ChromeOptions() # 无头模式开关,需要后台运行可取消注释 # options.add_argument("--headless") options.add_argument("--no-sandbox") options.add_argument("--disable-gpu") options.add_argument("--window-size=1920x1080") options.add_argument("--disable-extensions") chrome_driver = webdriver.Chrome( service=Service(ChromeDriverManager().install()), options=options ) def supplyvan_scraper(): with chrome_driver as driver: driver.implicitly_wait(15) URL = 'https://www.ifep.ro/justice/lawyers/lawyerspanel.aspx' driver.get(URL) time.sleep(3) link_elements = driver.find_elements(By.XPATH, "//div[@class='list-group']//a") for elem in link_elements: href = elem.get_attribute("href") # 跳过无href属性的标签,同时匹配目标域名前缀 if href and href.startswith("https://www.ifep.ro/"): print(href) if __name__ == "__main__": supplyvan_scraper()
关键修改说明
- 调整遍历逻辑:先通过
get_attribute("href")拿到a标签的链接字符串,增加非空判断,避免无href属性的a标签触发空值报错 - 修正方法名:将错误的
startsWith替换为Python原生的startswith()前缀判断方法 - 优化变量命名:将存元素列表的变量改为
link_elements、单个遍历元素改为elem,避免原代码中列表名单数、元素名复数的命名歧义 - 补充函数入口调用:原代码只定义了爬虫函数未执行,补充入口逻辑后可直接运行
内容的提问来源于stack exchange,提问作者Amen Aziz
相关产品推荐
相关产品推荐

