【问题标题】:Python locating elements in html using seleniumPython使用硒在html中定位元素
【发布时间】:2021-12-03 22:02:47
【问题描述】:

我是 python selenium 包的新手。我正在为 bookie 网站开发爬虫。

我无法点击并打开图片链接。

我的代码:

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
web = 'https://odibets.com/'
driver.get(web)

driver.implicitly_wait(3)
# btn = driver.find_element_by_css_selector('span.icon')""
btn = driver.find_element_by_xpath("//a[@href='/League'] and //span[text()='League']")

# <img src="https://s3-eu-west-1.amazonaws.com/odibets/img/menu/odi-league-2.png">

# //img[@src ="https://s3-eu-west-1.amazonaws.com/odibets/img/menu/odi-league-2.png"]
# //span[text()='League']
btn.click()

我得到以下异常。 raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //a[@href='/League'] and //span[text()='League'] because of the following error: TypeError: Failed to execute 'evaluate' on 'Document': The result is not a node set, and therefore cannot be converted to the desired type. (Session info: chrome=96.0.4664.45) Stacktrace: Backtrace: Ordinal0 [0x010D6903+2517251]

附件是来自 chrome 开发者工具和页面本身的快照代码。

【问题讨论】:

    标签: python-3.x selenium


    【解决方案1】:

    您的 href 是 /league 而不是 /League

    driver.find_element_by_xpath("//a[@href='/league'] [.//span[contains(.,'League')]]").click()
    

    这也适用于元素没有正确点击的原因。

    elem=driver.find_element_by_xpath("(//a[@href='/league'] [.//span[contains(.,'League')]])[1]")
    driver.execute_script("arguments[0].click()", elem)
    

    【讨论】:

    • 根据您提供的代码运行代码后出现以下异常。 File "C:\Program Files\Python38\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable (Session info: chrome=96.0.4664.45) Stacktrace: Backtrace: Ordinal0 [0x00CF6903+2517251] Ordinal0 [0x00C8F8E1+2095329] Ordinal0 [0x00B92710+1058576]链接还是打不开
    • 找到了解决办法。
    • 为什么看起来很复杂,click() 方法对第一个不起作用。
    • 关于点击功能不起作用所以我只是在a标签上使用了使用过的javascript。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 2020-02-03
    • 2020-07-23
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多