简体   繁体   中英

How do I find this HTML element with Python and Selenium?

This is an excerpt from the HTML source:

<div class="flex items-center mt-4">
    <svg style="fill: var(--color-reptile);" viewbox="0 0 16 16" width="24">

I want to find the svg element. This works:

e = driver.find_element_by_css_selector('div.flex.items-center.mt-4 [style]')
print(e.get_attribute('style')) # prints 'fill: var(--color-reptile);'

But how would I find this element directly without addressing the parent? I tried driver.find_element_by_css_selector('svg.fill\:.var\(--color-reptile\)\;') or driver.find_element_by_css_selector('.var\(--color-reptile\)\;') and all kind of different variations but every attempt just raises a "no such element" error.

It case this is the only svg element on the page I guess the following xpath should work:
//*[name()='svg']
Since, surely, it's not the only svg on the page you should add some more details like:
//*[name()='svg' and (@width='24')]

With css: svg[style*="fill: var(--color-reptile);"] , or svg[viewbox="0 0 16 16"] The first one looks for svg containing a string.

Try something like this //*[local-name()='svg'] and grab the style attribute

You are using . incorrectly. . indicates a class, not a style. That SVG does not have a class.

This CSS selector works

svg[style='fill: var(--color-reptile);']

but I would go with a variation of what you started with

div.flex.items-center svg

The style info on the SVG tag could easily change and then your locator is broken. It's less likely that the classes on the DIV parent will change and there's only one SVG child of that DIV so you should be good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM