如何使用 Selenium 和 Python 在网站 https://www.virustotal.com 中的 shadow-root(打开)中找到名字字段

人气:313 发布:2022-10-16 标签: python selenium-webdriver selenium queryselector shadow-dom

问题描述

我正在尝试自动化在病毒总站点上注册的过程,并为此在 python 中使用 selenium.但是在通过 id 获取元素时遇到问题.我被困在这任何帮助将不胜感激谢谢.这是我正在尝试的代码.

from selenium import webdriver从 selenium.webdriver.common.keys 导入密钥导入时间驱动程序 = webdriver.Chrome()driver.get('https://www.virustotal.com/gui/join-us')打印(驱动程序.标题)search = driver.find_element_by_id(first_name")search.send_keys(穆罕默德·阿米尔")search.send_keys(Keys.RETURN)时间.sleep(5)驱动程序退出()

解决方案

网站中的名字字段 并且您可以使用以下

I am trying to automate process of sign up on virus total site and for this using selenium in python. But having a problem while getting element by id. i am stuck in this any help will be appreciated thanks. here is my code i am trying.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver =webdriver.Chrome()
driver.get('https://www.virustotal.com/gui/join-us')
print(driver.title)
search = driver.find_element_by_id("first_name")
search.send_keys("Muhammad Aamir")
search.send_keys(Keys.RETURN)
time.sleep(5)
driver.quit()

解决方案

The First name field within the website https://www.virustotal.com/gui/join-us is located deep within multiple #shadow-root (open).

Solution

To send a character sequence to the First name field you have to use shadowRoot.querySelector() and you can use the following Locator Strategy:

Code Block:

from selenium import webdriver
import time

options = webdriver.ChromeOptions() 
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get("https://www.virustotal.com/gui/join-us")
time.sleep(7)
first_name = driver.execute_script("return document.querySelector('vt-virustotal-app').shadowRoot.querySelector('join-us-view.iron-selected').shadowRoot.querySelector('vt-ui-two-column-hero-layout').querySelector('vt-ui-text-input#first_name').shadowRoot.querySelector('input#input')")
first_name.send_keys("Muhammad Aamir")

Browser Snapshot:

References

You can find a couple of relevant discussions in:

Unable to locate the Sign In element within #shadow-root (open) using Selenium and Python

375