How can I parse html file using python and beautiful soup from html tag under html tag value?

Viewed 64

My html file contains same tag(<span class="fna">) multiple times. If I want to differentiate this tag then i need to look previous tag. Tag() under tag(<span id="field-value-reporter">). In beautiful soup, I can apply only on tag condition like, soup.find_all("span", {"id": "fna"}). This function extract all data for tag(<span class="fna">) but I need only which contain under tag(<span id="field-value-reporter")

Example html tags:

<div class="value">
    <span id="field-value-reporter">
        <div class="vcard vcard_287422" >
          <a class="email " href="/user_profile?user_id=287422" > 
            <span class="fna">Chris Pearce (:cpearce)
            </span>
          </a>
        </div>
    </span>
</div>

<div class="value">
    <span id="field-value-triage_owner">
        <div class="vcard vcard_27780" >
          <a class="email " href="/user_profile?user_id=27780"> 
            <span class="fna">Justin Dolske [:Dolske]
            </span>
          </a>
        </div>
    </span>
</div>
1 Answers

Use soup.select:

soup.select('#field-value-reporter a > span') # select for all tags that are children of a tag whose id is field-value-reporter

>>> [<span class="fna">Chris Pearce (:cpearce)</span>]

soup.select uses css selector and are, in my opinion, much more capable than the default element search that comes with BeautifulSoup. Note that all results are returned as list and contains everything that match.

Related