繁体   English   中英

How to locate the First name field within shadow-root (open) within the website https://www.virustotal.com using Selenium and Python

[英]How to locate the First name field within shadow-root (open) within the website https://www.virustotal.com using Selenium and Python

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

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()

网站https://www.virustotal.com/gui/join-us中的名字字段位于多个#shadow-root (open)深处。

病毒总数_名字


解决方案

要将字符序列发送到First name字段,您必须使用shadowRoot.querySelector()并且可以使用以下Locator Strategy

  • 代码块:

     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")
  • 浏览器快照:

virustotal_firstname_filled


参考

您可以在以下位置找到一些相关的讨论:

如果您查看网站的 HTML,您可以看到您的输入字段位于所谓的#shadowroot内。

在此处输入图像描述

这些 shadowroot 阻止您使用简单的find_element_by_id查找 shadowroot 中包含的元素。 您可以通过查找包含您要查找的元素的所有父 shadowroot 来解决此问题。 在每个 shadowroot 中,您需要使用 javascript 的 querySelector 并找到下一个 shadowroot,直到您可以访问您要查找的元素。

在您的情况下,您需要执行以下操作:

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)

# wait a bit untill form pops up
time.sleep(3)

# Retrieve the last shadowroot using javascript
javascript = """return document
.querySelector('vt-virustotal-app').shadowRoot
.querySelector('join-us-view').shadowRoot
.querySelector('vt-ui-text-input').shadowRoot"""
shadow_root = driver.execute_script(javascript)


# Find the input box
search = shadow_root.find_element_by_id("input")
search.send_keys("Muhammad Aamir")
search.send_keys(Keys.RETURN)
time.sleep(5)
driver.quit()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM