我在学习selenium的过程中,编写如下程序:
from selenium import webdriver
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.common.by import By
options = webdriver.EdgeOptions()
service = EdgeService(executable_path='msedgedriver.exe')
browser = webdriver.Edge(service=service, options=options)
browser.get('https://www.taobao.com')
login_btn = browser.find_element(By.NAME, '登录')
运行报错:
这个错误是页面上没有这个元素,打开浏览器,确实没有你写的这个登录按钮元素,你要定位的元素表达式写错了
from selenium import webdriver
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ex
options = webdriver.EdgeOptions()
service = EdgeService(executable_path='msedgedriver.exe')
browser = webdriver.Edge(service=service, options=options)
browser.get('https://www.taobao.com')
WebDriverWait(driver, 15).until(ex.visibility_of_element_located((By.XPATH, "//a[text()='亲,请登录']"))) # 等待这个按钮的出现
login_btn = browser.find_element(By.XPATH, "//a[text()='亲,请登录']")
【以下回答由 GPT 生成】
问题分析:
根据提供的代码,报错信息可能是由于无法定位到元素导致的。在代码中使用了By.NAME来定位元素,但是登录按钮的name属性可能不是'登录',导致无法找到该元素。
解决方案:
使用合适的选择器来定位元素。可以使用其他属性如id、class,或者使用xpath来定位元素。可以通过浏览器的开发者工具来查看元素的属性。
可以尝试使用显示等待,等待页面加载完成后再查找元素。这样可以确保元素已经存在在DOM树中才进行查找。
根据以上分析,下面是修改后的代码:
from selenium import webdriver
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.EdgeOptions()
service = EdgeService(executable_path='msedgedriver.exe')
browser = webdriver.Edge(service=service, options=options)
browser.get('https://www.taobao.com')
# 显示等待,等待登录按钮出现
login_btn = WebDriverWait(browser, 10).until(
EC.presence_of_element_located((By.XPATH, "//button[contains(text(), '登录')]"))
)
这样修改后,可以根据页面上登录按钮的具体属性来定位元素,如果找到了就可以继续执行后续的操作。
【相关推荐】