[Tutor] TypeError: argument 1 must be string or read-only character buffer, not instance
Kent Johnson
kent37 at tds.net
Thu Jun 5 17:15:40 CEST 2008
On Thu, Jun 5, 2008 at 8:06 AM, qsqgeekyogdty at tiscali.co.uk
<qsqgeekyogdty at tiscali.co.uk> wrote:
>>>> import os
>>>> from BeautifulSoup import BeautifulSoup
>>>> file = '/home/david/test/stack.html'
>>>> html = open(file, 'r')
>>>> soup = BeautifulSoup(html)
>>>> table = soup.find('table', {'class': 'order_tbl'})
>>>> for row in table.findAll('td', {'class': 'order_tbl_price'}):
>>>> for td in row:
>>>> price = float(td.contents[1].lstrip(' $'))
>>>> td.contents[1].replaceWith('$%0.2f' % (price * 0.85))
>
> My question now is do I have to close the html before I write to it,
Yes, it's a good idea.
> so that:
>
>>>> html.close()
>>>> html = open(file, 'w')
>>>> html.write(soup)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: argument 1 must be string or read-only character buffer,
> not instance
The error message is actually pretty informative. Argument 1 means the
argument you are passing to write(). It says it has to be a string or
a character buffer. You are passing it 'soup' with is an instance of
BeautifulSoup, not a string.
The fix is to ask for the soup as a string:
html.write(str(soup))
Kent
More information about the Tutor
mailing list