在 Python 中使用 WEBDRIVER 选择器出现错误

问题描述 投票:0回答:1

有一个类似于计算器的页面,我的目的是给定一个我已经建立的数字,创建一个代码来单击页面上的每个数字

try:
# Number to find
number_to_find= "71722336"

#loop
for number in number_to_find:
    selector = f"li.digits strong:contains('{number}')"
    boton_number= driver.find_element(By.CSS_SELECTOR, selector)
    boton_number.click()
    print("Number", number, "clicked!.")
    time.sleep(0.5)
except Exception as e:
print("Error to find and clicking the number:", e)

但是代码抛出以下错误: 按钮的结构是这样的

Message: javascript error: {"status":32,"value":"An invalid or illegal selector was specified"}
  (Session info: chrome=123.0.6312.106)
Stacktrace:
    GetHandleVerifier [0x00007FF788C270C2+63090]
    (No symbol) [0x00007FF788B92D12]
    (No symbol) [0x00007FF788A2EC65]
    (No symbol) [0x00007FF788A33D21]
    (No symbol) [0x00007FF788A36159]
    (No symbol) [0x00007FF788A36200]
    (No symbol) [0x00007FF788A7460C]
    (No symbol) [0x00007FF788A74ADC]
    (No symbol) [0x00007FF788AB5B37]
    (No symbol) [0x00007FF788A9701F]
    (No symbol) [0x00007FF788AB3412]
    (No symbol) [0x00007FF788A96D83]
    (No symbol) [0x00007FF788A683A8]
    (No symbol) [0x00007FF788A69441]
    GetHandleVerifier [0x00007FF78902262D+4238301]
    GetHandleVerifier [0x00007FF78905F78D+4488509]
    GetHandleVerifier [0x00007FF789057A6F+4456479]
    GetHandleVerifier [0x00007FF788D00606+953270]
    (No symbol) [0x00007FF788B9E5DF]
    (No symbol) [0x00007FF788B992B4]
    (No symbol) [0x00007FF788B993EB]
    (No symbol) [0x00007FF788B89C24]
    BaseThreadInitThunk [0x00007FFED6EF7344+20]
    RtlUserThreadStart [0x00007FFED84026B1+33]

按钮的结构是这样的

有谁知道导致此错误的原因或代码中有什么问题?

python loops selenium-webdriver
1个回答
0
投票

没有 CSS 选择器允许通过包含的文本搜索元素。几年前曾有过一次,但后来被砍掉了。现在执行此操作的唯一方法是使用 XPath。

一些建议...

  1. 避免使用异常来控制流程。使用
    .find_elements()
    并测试返回的集合是否为空。
  2. 不要将大块代码包装在
    try-except
    中。它只会让调试变得更加困难。让它抛出异常...一旦您学会了如何读取调用堆栈,它对于快速调试问题将非常有价值。
  3. 仅在特定例外情况下使用
    try-except
    ,并且仅在您要处理它们时使用,例如不要明白
    Exception
    ...它太宽泛了。

下面的代码应该可以工作

number_to_find = "71722336"
for number in number_to_find:
    digits = driver.find_elements(By.XPATH, f"//li[@class='digits']//strong[text()='{number}']")
    if digits:
        digits[0].click()
    else:
        print(f"Element containing <{number}> not found.")
    time.sleep(0.5)
© www.soinside.com 2019 - 2024. All rights reserved.