我在這里需要一些幫助,我嘗試填充一個文本框,但是當我檢查元素然后復制 xpath 時,它只會給我
/body/html
然后,我嘗試使用類名,但它不起作用
我該如何解決這個問題?
這是我的代碼:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('link_to_the_website')
driver.find_element_by_xpath('/body/html').send_keys('hello world')
textboxes = driver.find_element_by_xpath('/html/body')
這是我檢查文本框時的 html 代碼
<body marginwidth="0" marginheight="0" class="textarea from-control wysihtml5-editor placeholder" spellcheck="true" style="background-color: rgb(255, 255, 255); color: rgb(0, 0, 0); cursor: text; font-family: "Open Sans", sans-serif; font-size: 11px; font-style: normal; font-variant: normal; font-weight: 400; line-height: 16.5px; letter-spacing: normal; text-align: start; text-decoration: none solid rgb(0, 0, 0); text-indent: 0px; text-rendering: auto; word-break: normal; overflow-wrap: break-word; word-spacing: 0px;" contenteditable="true">type here......</body>
uj5u.com熱心網友回復:
- 您嘗試訪問的元素位于 iframe 內。
- 您應該使用顯式等待
- 你的定位器是錯誤的......
這可能會更好:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 20)
driver.get('link_to_the_website')
wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"(//iframe)[1]")))
textarea = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "body.textarea")))
textarea.send_keys(your_text)
UPD
第二個文本區域在另一個 iframe 內,但由于這些不是嵌套 iframe,為了從第一個 iframe 切換到第二個 iframe,您需要從第一個 iframe 切換到默認內容,然后切換到第二個 iframe . 通常,在處理完 iframe 中的元素后切換到 iframe 后,您應該切換到默認內容。
因此,要將文本寫入 2 個文本區域,您的代碼可能是這樣的:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 20)
driver.get('link_to_the_website')
wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"(//iframe)[1]")))
textarea1 = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "body.textarea")))
textarea1.send_keys(your_text1)
driver.switch_to.default_content()
wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"(//iframe)[2]")))
textarea2 = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "body.textarea")))
textarea2.send_keys(your_text2)
uj5u.com熱心網友回復:
當您右鍵單擊并檢查元素時,首先嘗試查看它是否具有名稱并相應地使用driver.find_element_by_name("")。
如果沒有可用的名稱,下一站應該是通過 css-selector 查找元素driver.find_element_by_css_selector("")。
Xpath 通常是您最不想使用的東西。順便說一句,您提供的鏈接在我復制時確實有一個 xpath。這將是/html/body/div[3]/div[1]/div[2]/div/form/div[1]/div/input[1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/393418.html
