如何在使用 Selenium 之前定位伪元素 ::before Python

How locate the pseudo-element ::before using Selenium Python

我正在使用 Selenium Python 来定位标签 element.I 想使用 ::before 来定位它,因为这是一个 pop window.

 <div class="crow" grp="0" grpname="Pizza Size">
    ::before
    <label class="label0" cid="1">
    <input type="radio" name="0" coname="M" sname="" price="9.99" value="392">M<b class="ip">9.99</b>
    </label>
    <label class="label0" cid="1"><input type="radio" name="0" coname="L" sname="" price="11.99" value="393">L<b class="ip">11.99</b>
    </label><div style="clear:both">
    </div>
    </div>

不知道怎么用::before定位,有哪位朋友可以帮忙吗?

如果我没记错的话,selenium 没有提供任何功能或 API 调用此功能。
您可以尝试解析 html,然后使用简单的 regular expression.
查找标签 希望这有帮助:)

Pseudo Elements

A CSS pseudo-element 用于设置元素指定部分的样式。它可以用于:

  • 设置元素的第一个字母或行的样式
  • 在元素内容之前或之后插入内容

::之后

::after 是一个伪元素,它允许您将内容插入到 CSS 的页面上(不需要它位于 HTML 中)。虽然最终结果实际上并不在 DOM 中,但它出现在页面上时就好像它在页面上一样,并且基本上是这样的:

CSS:

div::after {
  content: "hi";
}

::之前

::before 完全相同,只是它在 HTML 中的任何其他内容之前而不是之后插入内容。使用一个而不是另一个的唯一原因是:

  • 您希望生成的内容在位置上位于元素内容之前。
  • ::after 内容在源代码顺序中也是 "after",因此如果自然地相互堆叠,它将位于 ::before 之上。

提取

属性的演示

根据上面的讨论,您无法在 DOM Tree 中找到 ::before 元素,但您始终可以检索 伪元素的内容,即 ::before::after 元素。这是一个例子:

为了演示,我们将在 website:

中提取 ::after 元素(下面的快照)的内容

  • 代码块:

    from selenium import webdriver
    
    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://meyerweb.com/eric/css/tests/pseudos-inspector-test.html')
    script = "return window.getComputedStyle(document.querySelector('body>p.el'),':after').getPropertyValue('content')"
    print(driver.execute_script(script).strip())
    
  • 控制台输出:

    " (fin.)"
    

此控制台输出与content属性的完全匹配::after 元素如 HTML DOM:

中所示


这个用例

要提取 ::before 元素的 content 属性 的值,您可以使用以下解决方案:

script = "return window.getComputedStyle(document.querySelector('div.crow'),':before').getPropertyValue('content')"
print(driver.execute_script(script).strip())

结尾

一些相关文档: