ホームページ  >  記事  >  バックエンド開発  >  Selenium Python を使用してシャドウ ルートからデータを抽出する方法

Selenium Python を使用してシャドウ ルートからデータを抽出する方法

Linda Hamilton
Linda Hamiltonオリジナル
2024-10-19 06:38:30961ブラウズ

How to Extract Data from a Shadow Root Using Selenium Python?

Selenium Python を使用したシャドウ ルートからの情報の抽出

指定された URL のコンテキスト内 https://www.tiendasjumbo.co/ Buscar?q=mani では、#shadow-root (オープン) 内の要素から情報を抽出することが課題となります。次のコード スニペットは問題を示しています:

<code class="python">from selenium import webdriver
import time
from random import randint

driver = webdriver.Firefox(executable_path="C:\Program Files (x86)\geckodriver.exe")
driver.implicitly_wait(10)
time.sleep(4)

url = "https://www.tiendasjumbo.co/buscar?q=mani"
driver.maximize_window()
driver.get(url)
driver.find_element_by_xpath('//h1[@class="impulse-title"]')</code>

解決策:

Web ページ内の製品はシャドウ ルート内にカプセル化されています。これらの要素にアクセスするには、shadowRoot.querySelector() メソッドを使用する必要があります。次のコードは、この戦略を示しています。

<code class="python">driver.get('https://www.tiendasjumbo.co/buscar?q=mani')
item = driver.execute_script("return document.querySelector('impulse-search').shadowRoot.querySelector('div.group-name-brand h1.impulse-title span.formatted-text')")
print(item.text)</code>

出力:

La especial mezcla de nueces, maní, almendras y marañones x 450 g

参照:

  • [Selenium と Python を使用して #shadow-root (open) 内でサインイン要素を見つけることができません](https://stackoverflow.com/questions/66779988/unable-to-locate-the-sign-in-element-within- shadow-root-open-using-selenium-a)
  • [Selenium と Python を使用して、Web サイト https://www.virustotal.com 内のshadow-root (open) 内の名フィールドを見つける方法] (https://stackoverflow.com/questions/66820107/how-to-locate-the-first-name-field-within-shadow-root-open-within-the-website)

注:

Microsoft Edge および Google Chrome バージョン 96 では、シャドウ ルートの処理に変更が導入されました。最新情報については、次のリソースを参照してください:

  • Java: https://gist.github.com/chandrashekar4242/c2ef0878241f737cc89ec1878d60f974
  • Python: https://gist.github.com/hongtaocao/6409059fd2bb8d250f925b6b68c3a660
  • C#: https://gist.github.com/skcheidt/4a6a8bca561b403db94c7264a 5a24738
  • Ruby: https://gist.github.com/yuuuke-tanaka1/3493c57d228f759be374aeb0b64e51d9

以上がSelenium Python を使用してシャドウ ルートからデータを抽出する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
前の記事:Python の Sum 型次の記事:Python の Sum 型