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

Wil*_*iam 1 python selenium css-selectors pseudo-element selenium-webdriver

我正在使用 Selenium Python 来定位标签元素。我想使用::before来定位它,因为这是一个弹出窗口。

 <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>
Run Code Online (Sandbox Code Playgroud)

我不知道如何使用::before来定位它,有朋友可以帮忙吗?

Deb*_*anB 5

伪元素

CSS伪元素用于为元素的指定部分设置样式。它可用于:

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

::后

::after是一个伪元素,它允许您将内容从 CSS 插入页面(无需在 HTML 中)。虽然最终结果实际上并不在 DOM 中,但它在页面上看起来好像是这样,本质上是这样的:

CSS :

div::after {
  content: "hi";
}
Run Code Online (Sandbox Code Playgroud)

::前

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

  • 您希望生成的内容在位置上位于元素内容之前。
  • ::after内容也是“后”,在源极-顺序,所以它会在的顶部位置::before,如果堆叠在彼此的顶部自然。

提取的示范

根据上面的讨论,您无法::beforeDOM 树中定位元素,但您始终可以检索伪元素的内容,即::before::after元素。下面是一个例子:

为了演示,我们将提取::after网站中元素的内容(下面的快照):

after_element

  • 代码块:

    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())
    
    Run Code Online (Sandbox Code Playgroud)
  • 控制台输出:

    " (fin.)"
    
    Run Code Online (Sandbox Code Playgroud)

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

after_content


这个用例

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

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

奥特罗

几个相关文件: