Python Beautiful Soup: get text from element

Viewed 1830

I am looping through elements of type <td> but am struggling to extract the <td> text.

HTML:

<td class="cell">
 Brand Name 1
 <br/>
 (
 <a class="tip" title="This title">
  Authorised Resellers
 </a>
 )
</td>

: Desired output:

Brand name: Brand name 1
Brand distribution type: Authorised Reseller

I have tried:

for brand in brand_loop:
  print(brand.text)

But this does not print the text following the opening <td> tag ("Brand Name 1").

Any suggestions? Thanks!

3 Answers

Try

for brand in brand_loop:
  print(brand.text)
  print(brand.find('a').text)

You can only print the text of the selected element directly.

You can select <td class="cell"> and then .find_next(text=True) to get brand name, and then .find_next('a') to get brand distribution type.

For example:

txt = '''<td class="cell">
 Brand Name 1
 <br/>
 (
 <a class="tip" title="This title">
  Authorised Resellers
 </a>
 )
</td>'''


soup = BeautifulSoup(txt, 'html.parser')

brand_name = soup.select_one('td.cell').find_next(text=True)
bran_distribution = brand_name.find_next('a').text

print('Brand name:', brand_name.strip())
print('Brand distribution type:', bran_distribution.strip())

Prints:

Brand name: Brand Name 1
Brand distribution type: Authorised Resellers

You can use find() and next_element to get first td tag text.And to get a tag text simple use find(). You can try it:

from bs4 import BeautifulSoup
html_doc = '''<td class="cell">
 Brand Name 1
 <br/>
 (
 <a class="tip" title="This title">
  Authorised Resellers
 </a>
 )
</td>'''

soup = BeautifulSoup(html_doc,'lxml')
brand_name = soup.find("td").next_element.strip()
brand_distribution_type = soup.find("a").text.strip()
print('Brand name:', brand_name)
print('Brand distribution type:', brand_distribution_type)

Output will be:

Brand name: Brand Name 1
Brand distribution type: Authorised Resellers
Related