iT邦幫忙

0

如何在Python 中自動執行按鈕

A22 2023-05-07 13:36:381260 瀏覽
  • 分享至 

  • xImage

我用最簡單的句式測試程式:
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('https://www.google.com.hk//')
driver.implicitly_wait(6)
driver.find_element_by_xpath('//*[@id="gb"]/div/div[1]/div/div[2]/a').click()

但只能開啟網頁,不能點按圖片按鈕, 及回應如下:
Traceback (most recent call last):
File "C:\Users\CKH\Desktop\python\test10.py", line 6, in
driver.find_element_by_xpath('//*[@id="gb"]/div/div[1]/div/div[2]/a').click()
AttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'

DevTools listening on ws://127.0.0.1:50407/devtools/browser/dab26d82-e39e-4486-a407-250a1c3537b3
[2436:8420:0329/194839.136:ERROR:device_event_log_impl.cc(222)] [19:48:39.140] USB: usb_device_handle_win.cc:1046 Failed to read descriptor from node connection: 連結到系統的某個裝置失去作用。 (0x1F)
[2436:8420:0329/194839.141:ERROR:device_event_log_impl.cc(222)] [19:48:39.141] USB: usb_device_handle_win.cc:1046 Failed to read descriptor from node connection: 連結到系統的某個裝置失去作用。 (0x1F)

請幫忙?

你的按鈕是指你程式執行後會有個按鈕嗎,點他會跑到你要的網址嗎?
ccutmis iT邦高手 2 級 ‧ 2023-05-07 13:46:39 檢舉
find_element_by_xpath 是舊版本的用法
可能要改用 find_elements(By.XPATH, ... )
更多細節可在 google 搜 'selenium find_elements 教學'
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
海綿寶寶
iT邦大神 1 級 ‧ 2023-05-07 15:27:18

參考這篇看看合不合用

1
一級屠豬士
iT邦大師 1 級 ‧ 2023-05-08 07:13:56

https://selenium-python-zh.readthedocs.io/en/latest/locating-elements.html

要補上 import By , 改用 find_element(By.XPATH...), 這樣的方式.

from selenium.webdriver.common.by import By

driver.find_element(By.XPATH, '//button[text()="Some text"]')
driver.find_elements(By.XPATH, '//button')
huahualiu iT邦新手 2 級 ‧ 2023-05-09 09:28:07 檢舉

剛好最近讀到相關問題
補充一下
新版本 selenium 套件已經不支援 find_element_by_xpath 的方法
所以請全部改用上面的 By 方式抓網頁元素

雖然版主沒說是用哪個版本 Selenium
但我猜大概是因為這關係XD

我要發表回答

立即登入回答