Selenium 单击 JS 按钮 - Python?

Selenium Click JS Button - Python?

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

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

回复按钮具有以下 X 路径:

'/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",但也没有用。

这个 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()

单击该按钮会打开一个 "show phone number" 弹出窗口(可能位于 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 的按钮。您可以立即复制 "class" 部分 -> class="reply-button js-only"

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

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

如果"find elements" returns一个结果,通常你应该没问题。您可以看到,我所做的只是将 class 粘贴到其中:driver.find_elements_by_xpath('//*[@ 和这个 ]')

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

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

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

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

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