-1

In the webbrowser I need to extract this element:

<line stroke="#003088" stroke-width="15.562500357627869" stroke-linecap="round" marker-end="url(#arrowhead-pb)" opacity="0.4" x1="166.00000381469727" y1="431.6000099182129" x2="166.00000381469727" y2="309.17500710487366" cgHash="531.2000122070312,531.2000122070312,c2,c4,paleBlue"></line>

This element is not interactable but I still need so save the x1, x2, y1, y2 coordinates into variables. The only find option that worked for me was driver.find_element_by_tag_name('line') but this return the coordinates {'x': 611, 'y': 372} which is clearly not what I want.

My question: is there any way I can extract the exact coordinates from the webbrowser? Mainly x1, x2, y1, y2.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Bente61
  • 21
  • 3

2 Answers2

1

The <line> attribute is associated with the elements which are from the SVG namespace. As an example:

<svg height="210" width="500">
  <line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" />
</svg>

To print the value of x1 coordinate you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    print(driver.find_element(By.CSS_SELECTOR, "svg line").get_attribute("x1"))
    
  • Using XPATH and name():

    print(driver.find_element(By.XPATH, "//*[name()='svg']//*[name()='line']").get_attribute("x1"))
    
  • Using XPATH and local-name():

    print(driver.find_element(By.XPATH, "//*[local-name()='svg']/*[local-name()='title']").get_attribute("x1"))
    

Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.name[title='Download']"))).get_attribute("x1"))
    
  • Using XPATH and name():

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[name()='svg']//*[name()='line']"))).get_attribute("x1"))
    
  • Using XPATH and local-name():

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[local-name()='svg']/*[local-name()='title']"))).get_attribute("x1"))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

References

You can find a couple of relevant discussions on interacting with SVG element in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

to get x you can use: ( similarly do for y , z etc)

driver.find_element_by_tag_name('line').get_attribute("x")

you can get any element attribute , x , y etc are not coordinates but attribute of that element

PDHide
  • 18,113
  • 2
  • 31
  • 46