Home > Blockchain >  How to get the value of an element within a tag?
How to get the value of an element within a tag?

Time:04-13

<div >
    <div>
        <play-js data-account="1234567890" data-id="32667_32797">
        </play-js>
    </div>
</div>

I want to get the values of data-account and data-id which are elements within play-js tag.

elemname = driver.find_elements_by_xpath('xpath.../div/play-js')

I tried like below, but I couldn't get the value.

With javascript, I was able to import it with the code below.

var elems = document.querySelectorAll('.player__AAtt play-js');
console.log(elems[0].dataset.account)
console.log(elems[0].dataset.dataid)

How can I get the value of an element within a tag rather than the tag itself?

CodePudding user response:

You can use the .get_attribute() method:

elemname = driver.find_elements_by_xpath('xpath.../div/play-js')

elemname.get_attribute("data-account")

CodePudding user response:

In python we use BeautifulSoup mostly for parsing the html page. Here the code that will help you to get the value of all the play-js element in the provided html file.

from bs4 import BeautifulSoup

res_page = """
<div >
    <div>
        <play-js data-account="1234567890" data-id="32667_32797">
        </play-js>
    </div>
</div>
"""

soup = BeautifulSoup(res_page, 'html.parser')
output_list = soup.find_all('play-js')
data_account_list = [data_account['data-account'] for data_account in output_list]
data_id_list = [data_id['data-id'] for data_id in output_list]

print(data_account_list)
print(data_id_list)

The output is:

['1234567890']
['32667_32797']
  • Related