首页  >  文章  >  后端开发  >  如何使用 Selenium Python 从 Shadow Root 中提取数据?

如何使用 Selenium Python 从 Shadow Root 中提取数据?

Linda Hamilton
Linda Hamilton原创
2024-10-19 06:38:30962浏览

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>

解决方案:

网页中的产品封装在影子根中。要访问这些元素,必须使用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 在网站 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/4a6a8bca561b403db94c7264a5a2473 8
  • 红宝石: https://gist.github.com/yuusuke-tanaka1/3493c57d228f759be374aeb0b64e51d9

以上是如何使用 Selenium Python 从 Shadow Root 中提取数据?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn