Python: BeautifulSoup - get an attribute value based on the name attribute

后端 未结 7 1788
抹茶落季
抹茶落季 2020-11-27 10:38

I want to print an attribute value based on its name, take for example


I want to do something

7条回答
  •  迷失自我
    2020-11-27 11:16

    One can also try this solution :

    To find the value, which is written in span of table

    htmlContent


    ID Name
    ID123 Bonny

    Python code


    soup = BeautifulSoup(htmlContent, "lxml")
    soup.prettify()
    
    tables = soup.find_all("table")
    
    for table in tables:
       storeValueRows = table.find_all("tr")
       thValue = storeValueRows[0].find_all("th")[0].string
    
       if (thValue == "ID"): # with this condition I am verifying that this html is correct, that I wanted.
          value = storeValueRows[1].find_all("span")[0].string
          value = value.strip()
    
          # storeValueRows[1] will represent  tag of table located at first index and find_all("span")[0] will give me  tag and '.string' will give me value
    
          # value.strip() - will remove space from start and end of the string.
    
         # find using attribute :
    
         value = storeValueRows[1].find("span", {"name":"spanId"})['class']
         print value
         # this will print spanclass
    

提交回复
热议问题