Search code examples
css-selectorspython-requests-html

Why this css selector is not working properly?


While Extracting 1st Company's name using css selectors output is perfect But Second selector "sel2" returns None

from requests_html import HTMLSession
session = HTMLSession()

page=session.get("https://www.moneycontrol.com/stocks/marketstats/indcomp.php")

#print(page)

sel1 = '#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div.bsr_table.hist_tbl_hm.PR.Ohidden > table > tbody > tr:nth-child(1) > td.PR > span.gld13.disin'
sel2 = '#mc_content > section > section > div.clearfix.stat_container > div.columnst.FR.wbg.brdwht > div > div.bsr_table.hist_tbl_hm.PR.Ohidden > table > tbody > tr:nth-child(2) > td.PR > span.gld13.disin'

temp=page.html.find(sel1, first=True).text
print(temp.strip("\n Add to \n Watchlist | Portfolio"))

temp=page.html.find(sel2, first=True).text
print(temp.strip("\n Add to \n Watchlist | Portfolio"))

Output Needed
Carborundum
Grindwell Norto
For More refernece and choosing selectors:- enter image description here

https://www.moneycontrol.com/stocks/marketstats/indcomp.php


Solution

  • In the case of this particular page, you can use much simpler selectors:

    sel1 = 'span > a'
    temp=page.html.find(sel1)
    print(temp[0].text)
    print(temp[1].text)
    

    Output:

    Carborundum
    Grindwell Norto