0

I am trying to open a webpage and write the page in a text file. This is the code so far and its not working. Cam anyone give me a general idea about what I am doing wrong?

import urllib
opener = urllib.FancyURLopener({})
f = opener.open("http://www.python.org/")
g = open("data2.txt", "w")
g.write(str(f))      # str() converts to string
g.close()

All I gets when executing the code is text file data2.txt with below line only:

<addinfourl at 43347592L whose fp = <socket._fileobject object at 0x000000000294C480>>
Abhishek dot py
  • 909
  • 3
  • 15
  • 31

3 Answers3

2

There are better tools for this job, like requests. For example

import requests

url = 'http://www.python.org'
r = requests.get(url)

text_file = open("Output.txt", "w")
text_file.write(r.text)
text_file.close()
sidj9n
  • 29
  • 5
0
  import urllib

  opener = urllib.FancyURLopener({})
  f = opener.open("http://www.python.org/")
  lines = f.read() # you missed this
  g = open("data2.txt", "w")
  g.write(str(lines))      # str() converts to string
  g.close()
0

You can use 'grab' module for this too.

from grab import Grab

g = Grab()
r = g.go('http://www.python.org')
open('page.htm', 'w').write(r.body)
Anton Barycheuski
  • 712
  • 2
  • 9
  • 21