Selenium 无法通过 id 找到元素,但它存在
Selenium cant find element by id, yet it exists
所以基本上我的脚本会转到我商店的 product-creation 页面,然后登录,重定向后应该输入产品标题。
为此我想使用 selenium,因为这个商店系统没有对我有用的 API 功能。
实现此目的的代码如下:
from selenium import webdriver
import time
browser = webdriver.Firefox()
url3 = 'https://mywebsite.net/admin#/sw/product/create/base'
browser.get(url3)
swu = 'admin'
swp = 'password'
browser.find_element_by_id('sw-field--username').send_keys(swu)
browser.find_element_by_id(
'sw-field--password').send_keys(swp)
browser.find_element_by_class_name('sw-button__content').click()
time.sleep(5)
browser.find_element_by_id(
'sw-field--product-name').send_keys('dsdsdsdssds')
但是,我的脚本可以通过 ID 完美识别管理员和密码字段,但在登录和重定向后它无法识别产品标题字段。
商店系统是shopware 6
因为您没有提供任何 HTML 来处理(或 reprex), I can't give an answer specific to your use case. However, the solution is likely to be that you need to use Selenium's expected conditions:
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.Firefox()
driver.get("https://mywebsite.net/admin#/sw/product/create/base")
...
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
finally:
driver.quit()
元素对 selenium 不可见的另一个值得注意的原因是它包含在 iframe
中。如果是这种情况,您需要按照 documentation.
中的说明使用 switch_to_frame
所以基本上我的脚本会转到我商店的 product-creation 页面,然后登录,重定向后应该输入产品标题。
为此我想使用 selenium,因为这个商店系统没有对我有用的 API 功能。
实现此目的的代码如下:
from selenium import webdriver
import time
browser = webdriver.Firefox()
url3 = 'https://mywebsite.net/admin#/sw/product/create/base'
browser.get(url3)
swu = 'admin'
swp = 'password'
browser.find_element_by_id('sw-field--username').send_keys(swu)
browser.find_element_by_id(
'sw-field--password').send_keys(swp)
browser.find_element_by_class_name('sw-button__content').click()
time.sleep(5)
browser.find_element_by_id(
'sw-field--product-name').send_keys('dsdsdsdssds')
但是,我的脚本可以通过 ID 完美识别管理员和密码字段,但在登录和重定向后它无法识别产品标题字段。
商店系统是shopware 6
因为您没有提供任何 HTML 来处理(或 reprex), I can't give an answer specific to your use case. However, the solution is likely to be that you need to use Selenium's expected conditions:
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.Firefox()
driver.get("https://mywebsite.net/admin#/sw/product/create/base")
...
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
finally:
driver.quit()
元素对 selenium 不可见的另一个值得注意的原因是它包含在 iframe
中。如果是这种情况,您需要按照 documentation.
switch_to_frame