You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决WebDriver对象无find_element_by_css_selector属性的报错问题

问题解决:AttributeError: 'WebDriver' object has no attribute 'find_element_by_css_selector'

这个错误是因为你使用的Selenium 4.x及以上版本已经移除了find_element_by_css_selector这类旧的元素定位API,必须改用基于By类的新语法。

修改后的完整代码

from selenium import webdriver
from selenium.webdriver.common.by import By  # 新增导入By类

def scrape_coordinates(city):
    # 初始化Chrome驱动
    driver = webdriver.Chrome()
    driver.maximize_window()
    # 打开谷歌地图
    driver.get("https://maps.google.com")
    # 定位搜索栏并输入城市名称
    search_bar = driver.find_element(By.CSS_SELECTOR, "input[aria-label='Search Google Maps']")
    search_bar.send_keys(city)
    search_bar.submit()
    # 等待地图加载并定位坐标元素
    driver.implicitly_wait(5)
    coordinates_element = driver.find_element(By.CSS_SELECTOR, ".QSFF4-text")
    # 获取坐标文本内容
    coordinates_text = coordinates_element.get_attribute("textContent")
    latitude, longitude = coordinates_text.split(",")
    # 关闭浏览器
    driver.quit()
    return latitude.strip(), longitude.strip()

# 获取用户输入
city_input = input("请输入要查询坐标的城市名称:")
# 爬取坐标
latitude, longitude = scrape_coordinates(city_input)
print(f"{city_input}的坐标:纬度 - {latitude},经度 - {longitude}")

额外注意事项

  • 确保ChromeDriver版本与本地Chrome浏览器版本完全匹配,否则会出现驱动初始化失败问题
  • 谷歌地图页面元素可能随时更新,若后续出现定位失败,需重新校验CSS选择器的有效性
  • 推荐使用显式等待替代隐式等待(如WebDriverWait配合expected_conditions),能更精准地等待元素加载,提升代码稳定性

内容的提问来源于stack exchange,提问作者Alex Benj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:35:06