如何使用Selenium WebDriver点击 "复制"?

问题描述 投票:0回答:1

我如何从这个URL点击 "复制 "按钮?https:/www.w3resource.comjava-exercisesbasicjava-basic-exercise-249.phpenter image description here

我需要点击的标签被标记为 "复制"

我已经尝试了多种 "查找元素 "的方法,但我一直收到错误信息,如没有这样的元素,在这种情况下,我如何选择 "复制 "参考,用什么方法点击 "复制"?

button = driver.find_elements_by_class_name('toolbar-item') #not working
driver.findElementByClassName("a.cc_btn.cc_btn_accept_all") #not working
driver.find_element_by_css_selector("toolbar").click() #not working
driver.findElementByClassName("toolbar-item").click() #not working

在这种情况下,我如何选择 "复制 "参考,以及用什么方法点击 "复制"? 此外,当 "复制 "按钮被点击时,我如何能将内容粘贴到文本文件。

这些是我得到的其他错误。

错误。

Traceback (most recent call last):
  File "untitled.py", line 27, in <module>
    driver.find_element_by_css_selector("toolbar-item").click()
  File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 598, in find_element_by_css_selector
    return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
  File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
    'value': value})['value']
  File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"toolbar-item"}
  (Session info: chrome=81.0.4044.138)

还有

NoSuchElementException: Message: Unable to locate element:

enter image description here

selenium web-scraping css-selectors webdriver web-scraping-language
1个回答
1
投票

要点击 "复制 "按钮 Copy 诱发 WebDriverWait()并等待 presence_of_element_located()和下面的xpath.你需要滚动元素来点击。

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

driver = webdriver.Chrome()
driver.get("https://www.w3resource.com/java-exercises/basic/java-basic-exercise-249.php")
copybtn=WebDriverWait(driver,15).until(EC.presence_of_element_located((By.XPATH,"//a[text()='Copy']")))
copybtn.location_once_scrolled_into_view
copybtn.click()

你也可以使用下面的css选择器。

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

driver = webdriver.Chrome()
driver.get("https://www.w3resource.com/java-exercises/basic/java-basic-exercise-249.php")
copybtn=WebDriverWait(driver,5).until(EC.presence_of_element_located((By.CSS_SELECTOR,".toolbar-item>a")))
driver.execute_script("arguments[0].scrollIntoView();", copybtn)
copybtn.click()
© www.soinside.com 2019 - 2024. All rights reserved.