4

I am trying to display a webpage, but since it does not view the object as a string, it does not properly display newlines (it displays \n). How can I make a result a string properly as this does not seem to be working. Thanks!

result = urllib.request.urlopen(requesturl).read()
return str(result)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
acb10824
  • 61
  • 1
  • 1
  • 2
  • The question is not clear. The fact that it contains `\n` does not make it an invalid string. Is this at all specific to `pyqt` or are you simply looking to print a single string broken up by new lines? – roganjosh Feb 13 '17 at 20:26
  • I want the \n character to actually print a new line, however since the type seems to be httpresponse, it prints the character \n instead of a new line. – acb10824 Feb 14 '17 at 18:10

1 Answers1

4

As explained in this post, you need to handle the character encoding of the response you have from the Content-Type. urllib provides a handy way to get at this from the headers using the get_content_charset method.

from urllib.request import urlopen

with urlopen(request_url) as response:
  html_response = response.read()
  encoding = response.headers.get_content_charset('utf-8')
  decoded_html = html_response.decode(encoding)
  return decoded_html
Benjamin Rowell
  • 1,371
  • 8
  • 16