似乎无法使用 selenium 和 python 单击元素

Can't seem to be able to click on an element using selenium and python

我正在尝试单击 "most helpful first" 下拉列表并将其更改为 android Playstore 应用的最新评论。

https://play.google.com/store/apps/details?id=com.nintendo.zama&showAllReviews=true

通过查找 class 和 xpath 尝试了多种方法,例如下面的方法,但没有任何效果。

new_comments = driver.find_element_by_link_text('"Most helpful first"').click()

不是这个元素,你应该使用其他元素并使用 send_keys,要检查它你需要按 F12 并注意突出显示 "Most helpfull first" 字段的元素。它是您已经在寻找的那个元素的父元素,对我来说是这样的:

from selenium.webdriver.common.keys import Keys
driver.find_element_by_xpath('//*[@class="MocG8c UFSXYb LMgvRb KKjvXb"]').send_keys(Keys.ARROW_DOWN, Keys.ARROW_DOWN)

然后你看到了另一个列表,你需要从列表中找到好的元素:

driver.find_elements_by_xpath('//div[@jsname="wQNmvb"]')[-3].click()

我使用索引 -3,因为有 6 个元素具有相同的 xpath。

您应该对 link 文本使用 find_element_by_link_text 方法。

例如,考虑这个页面来源:

<html>
<body>
  <p>Are you sure you want to do this?</p>
  <a href="continue.html">Continue</a>
  <a href="cancel.html">Cancel</a>
</body>
<html>

因此,如果您想通过 link 文字点击:

continue_link = driver.find_element_by_link_text('Continue')
continue_link = driver.find_element_by_partial_link_text('Conti')

但是,在你的例子中,'Most helpful first' 文本不是 link 文本,它在 <span> 标签中。

所以可以使用driver.find_element_by_css_selector方法或者driver.find_element_by_xpath方法:

CSS:

driver.find_element_by_css_selector('.KKjvXb > span');

XPATH:

driver.find_element_by_xpath("//span[text() = 'Most helpful first']");

在文本为最有帮助的元素上click()首先然后在文本为最新的元素上click() 您需要为所需的 element_to_be_clickable() 引入 WebDriverWait 并且您可以使用以下 :

  • 使用XPATH:

    driver.get('https://play.google.com/store/apps/details?id=com.nintendo.zama&showAllReviews=true')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//h2[text()='Reviews']//following::span[text()='Most helpful first'][1]"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//h2[text()='Reviews']//following::span[text()='Most helpful first'][1]//following::span[text()='Newest']"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

浏览器快照:

我做到了。

dropdown = driver.find_element_by_xpath('//*[@id="fcxH9b"]/div[4]/c-wiz/div/div[2]/div/div[1]/div/div/div[1]/div[2]/c-wiz/div[1]/div/div[1]/div[2]').click()
sleep(2)
new_comments = driver.find_element_by_xpath('//*[@id="fcxH9b"]/div[4]/c-wiz/div/div[2]/div/div[1]/div/div/div[1]/div[2]/c-wiz/div[1]/div/div[2]/div[1]').click()

在浏览器控制台中尝试并使用 javascript executor::

执行它

$x("(//span[text()='Most helpful first'])[1]")[0].click();