简体   繁体   English

如何在Python中使用Selenium单击按钮?

[英]How do I click a button using Selenium in Python?

I'm trying to crawl review data on an app from a Google Play website page using Python and Selenium. 我正在尝试使用Python和Selenium从Google Play网站页面上抓取应用程序上的评论数据。 What I'm trying to do here is to click the "Full Review" button to see the entire text of each review. 我在这里要做的是单击“完整评论”按钮以查看每个评论的全文。

But I keep running into these errors each time: 但是我每次都会遇到这些错误:

ElementNotInteractableException: Message: element not interactable

or 要么

AttributeError: 'list' object has no attribute 'click'

or 要么

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".LkLjZd ScJHi OzU4dc  "}

The element for the button is this: 该按钮的元素是这样的:

<button class="LkLjZd ScJHi OzU4dc  " jsaction="click:TiglPc" jsname="gxjVle">Full Review</button>

The xpath for the button is this: 按钮的xpath是这样的:

//*[@id="fcxH9b"]/div[4]/c-wiz/div/div[2]/div/div[1]/div/div/div[1]/div[2]/div/div[26]/div/div[2]/div[2]/span[1]/div/button

And this is the code I'm using for xpath: 这是我用于xpath的代码:

full_review = driver.find_elements_by_xpath('//*[@id="fcxH9b"]/div[4]/c-wiz/div/div[2]/div/div[1]/div/div/div[1]/div[2]/div/div[26]/div/div[2]/div[2]/span[1]/div/button')
full_review.click()

I can't find the button by class name, xpath or anything. 我找不到通过类名,xpath或任何东西的按钮。 Could anyone help me figure out this problem? 谁能帮我解决这个问题? In addition, is it possible to find the element by jsname? 另外,是否可以通过jsname查找元素? I would really appreciate if you could help. 如果您能提供帮助,我将不胜感激。

Avoid using xpath whenever possible, it's the most brittle selector. 尽可能避免使用xpath,因为它是最脆弱的选择器。

id > CSS > Xpath id> CSS> Xpath

For your button, this css selector should work: 对于您的按钮,此CSS选择器应该起作用:

button[jsname='gxjVle']

You'll probably need to specify the child as that probably won't be unique 您可能需要指定孩子,因为孩子可能不是唯一的

  1. Your XPath selector is a little bit flaky, you can simplify it to be something like: 您的XPath选择器有些不稳定,您可以将其简化为:

     //button[text()='Full Review'] 
  2. You're using the wrong function, if you're looking for a single unique element you should be using WebDriver.find_element_by_xpath one, mind that element , not elements 您使用的是错误的函数,如果要查找单个唯一元素,则应使用WebDriver.find_element_by_xpath一个,请注意该element ,而不是elements
  3. It's better to use Explicit Wait just in case element is not immediately available in DOM (for example if you're testing application built using AJAX technology ) 最好使用Explicit Wait ,以防万一DOM中没有立即可用的元素(例如,如果您正在测试使用AJAX技术构建的应用程序

Assuming all above: 假设以上所有:

full_review = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Full Review']")))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM