簡體   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