Best approach to get attribute text with BeautifulSoup

Viewed 44

What would be the best way to get the text of the items class="field__label" y class="field__item" in the following code

Taking into consideration that there are other tags with the same class outside the div class="fieldset-wrapper" I just need the ones inside this tag.

HTML Example:

<div class="fieldset-wrapper">

  <div class="field field--name-field-adresse-strasse-nr field--type-string field--label-inline clearfix">
    <div class="field__label">TEXT</div>
    <div class="field__item">TEXT</div>
  </div>

  <div class="field field--name-field-adresse-plz-ort field--type-string field--label-inline clearfix">
    <div class="field__label">TEXT</div>
    <div class="field__item">TEXT</div>
  </div>

  <div class="field field--name-field-adressen-bundesland field--type-entity-reference field--label-inline clearfix">
    <div class="field__label">TEXT</div>
    <div class="field__item">TEXT</div>
  </div>

</div>
1 Answers

You can use css selectors to ensure that your target elements are descendants of the div class="fieldset-wrapper" element:

for item in  soup.select('div.fieldset-wrapper div.field__item, div.fieldset-wrapper  div.field__label'):
    print(item.text)
Related