【问题标题】:Selenium Click JS Button - Python?Selenium 单击 JS 按钮 - Python?
【发布时间】:2020-07-28 21:47:43
【问题描述】:

是的,有类似的问题,但是在阅读它们后,我无法找到解决问题的方法。

以下情况:我正在尝试单击“https://charleston.craigslist.org/ctd/d/charleston-2018-nissan-sentra-sedan-4d/7108660907.html”上的“回复”按钮,执行此单击后会出现一个弹出窗口,我将在其中单击另一个按钮,但让我们从第一个按钮作为“回复”开始" 点击本身就很麻烦。

回复按钮的 X-Path 如下:

'/html/body/section/section/header/div[2]/div/button'

说到源代码是:

<button role="button" class="reply-button js-only" data-href="/__SERVICE_ID__/chs/ctd/7108660907">
      reply
    </button> 

(参见上述网站上的代码)。

但是,我使用 Selenium (Python) 的方法不起作用:

reply_button = '/html/body/section/section/header/div[2]/div/button'
driver.get('https://charleston.craigslist.org/ctd/d/charleston-2018-nissan-sentra-sedan-4d/7108660907.html')

driver.find_element_by_xpath(reply_button).click()

每次我尝试时,网站都会正确加载(即使实现 time.sleep(x))并尝试单击按钮,但这失败并且网站只是刷新 - 我的猜测是他们要么重新识别浏览器Selenium 控制,点击是不合法的,或者我在我的代码中没有捕捉到任何正确的东西。任何人都可以帮忙吗?

顺便说一句,我已经尝试过搜索“by_class_name”,但也没有用。

【问题讨论】:

    标签: python selenium button click refresh


    【解决方案1】:

    这个 Xpath:'/html/body/section/section/header/div[2]/div/button' 就像你得到一张带有 step forward until you see a car then turn left 30° then step forward until you see a tree then hop twice then go to the second house to your right 这样的指令的地图。使用不安全,请避开此类路径。如果页面布局发生变化,您的路径可能会失效。

    试试这个:

    button = driver.find_element_by_xpath('//*[@class="reply-button js-only"]')
    button.click()
    

    点击按钮会打开一个“显示电话号码”弹出窗口(可能位于driver.find_element_by_xpath('//*[@class="show-phone"]'))。

    解释:

    如果您想要正确的 Xpath,请检查您想要与之交互的内容。你要点击的按钮是这样的:

    <button role="button" class="reply-button js-only" data-href="/__SERVICE_ID__/chs/ctd/7108660907">
          reply
        </button>
    

    您可以看到它没有“id”标签,但它是一个具有特定类的按钮。您可以立即复制“类”部分 -> class="reply-button js-only"

    现在你可以检查它是否足够独特:

    driver.find_elements_by_xpath('//*[@class="reply-button js-only"]')
    

    如果“查找元素”返回单个结果,通常应该没问题。你可以看到我所做的只是将类粘贴在这个里面:driver.find_elements_by_xpath('//*[@ 和这个]')

    如果需要更准确,可以指定为按钮:

    driver.find_element_by_xpath('//button[@class="reply-button js-only"]')
    

    或者它是具有类的元素的直接子元素:class="actions-combo",因此更安全的路径是:

    driver.find_element_by_xpath('//*[@class="actions-combo"]/button[@class="reply-button js-only"]')
    

    此模式适用于所有 web 元素属性,而不仅仅是类。您也可以使用role="button" 进行更多过滤。查找 Xpath,它是一个非常整洁的东西。

    【讨论】:

    • 您是如何获得这个替代 XPath 的?
    • 我会补充答案,等等。
    • 感谢您的深入解释。帮了我很多,并且能够正确点击回复按钮:) 还有一个问题(如果您不介意回答):您将如何检查“//*[@class="show-phone"] " 可用(然后单击它以最终取消隐藏数字和/或能够复制文本)?
    • 为此,请检查:stackoverflow.com/questions/28110008 正确的做法是:EC.element_to_be_clickable((By.XPATH, "myXpath")))
    • 这是处理这个问题的天才方法!我想到了一个 try/except 块,但这不需要任何等待时间(除非你使用 time.sleep(x))。非常感谢你的帮助!
    猜你喜欢
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2021-01-31
    • 2020-07-30
    • 2021-03-31
    • 2020-08-06
    • 2021-08-27
    相关资源
    最近更新 更多