How to extrac data from tag attribute using Selenium and Python?

Viewed 163

I'm using Selenium to extract student marks. Now I want to get mark's weight (every mark has it's own weight) and use it later to calculate students weighted average.

Here is the tag that contains all informations.

<span class="score-font color-f04c4c" data-qtip="Code: II<br/>Description: abcd/June<br/>Weight: 2<br/>Date: 28.02.2020<br/>Teacher:xxx">5</span>

My question is how to extrct:

"Weight: 2"

3 Answers

I think your HTML may be a little messed up so make sure you copy the exact HTML for the future. There should be (if I'm not mistaken) an ending quotation mark after "Code: II" otherwise all the br tags are just rendered as strings. Since the information you are trying to get is the text of that element, all you need to do is use the .text attribute in Selenium

my_element = browser.find_element_by_xpath('//span[@id="some_id"]/whatever/path')
my_element_text = my_element.text #grabbing the text property of the element and storing it as a string

You can tack the .text onto the end of the first line if you just want to make it one line. Now just do some post processing on that string and get rid of whatever you don't want (e.g. Teacher, Date)

you can use

my_element_text= browser.find_element_by_xpath('//span[contains(.,'Weight')]').text

//Now use substring function to get desired text.Assuming Weight starts from character 32

my_element_text[32:42]

Output: Weight: 2

As values you want are stored attribute data-qtip. Use getAttribute method to get value of this attribute.

att_Value= driver.find_element_by_tag_name('<xpath for containing span>').get_attribute("data-qtip")

Now as there are multiple values in above text and are separated by line break </br>, you can convert above string into a list and extract whatever information you need.

values = att_Value.split("<br/>")
for v in values:
    print(v)

Above will print like below.You can use list index like values[0] will give you code, values[2] will give you code Weight and etc.

Out put:

enter image description here

Related