0

im trying print html using beautifulsoup like this:

load = urllib2.urlopen(url)
soup = BeautifulSoup(load, 'lxml')
characteristics = soup.find('table', { 'class' : 'characteristics-table'})
print characteristics

Get this:

<table class="characteristics-table">
<tr class="characteristics alt">
<td class="name">
Zīmols
</td>
<td>
Emporio Armani</td>
</tr>
<tr class="characteristics">
<td class="name">
<b>Mehānisma tips</b>
</td>
<td>
<b>Mehāniskie automātiskie</b></td>
</tr>...

But need something like this:

<table class="characteristics-table"><tr class="characteristics alt"><td class="name">Zīmols</td><td>...

How to do it?

2 Answers 2

2

If you just want to remove the newlines in characteristics, then use str.replace to remove them, by replacing newlines with an empty string '':

print str(characteristics).replace('\n', '').replace('\r\n', '')

The first one replaces unix-style newlines and the second one, applied to the result of the first, replaces windows-style newlines.

Edit: the .replace has to be applied to the str() of the returned obj from beautifulsoup's find.

1
  • returns: characteristics.replace('\n', '').replace('\r\n', '') TypeError: 'NoneType' object is not callable
    – J. Wash
    Oct 28, 2017 at 2:55
1
''.join(characteristics.split('\n'))   #or \r\n on Windows
2
  • returns: ''.join(characteristics.split('\n')) TypeError: 'NoneType' object is not callable
    – J. Wash
    Oct 28, 2017 at 2:56
  • In your code, the type of your variable characteristics is 'bs4.element.Tag'. As with aneroid's answer above: you need to convert it to a string first. So do: ''.join(str(characteristics).split('\n'))
    – trajekolus
    Oct 28, 2017 at 3:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.