2

Hello i want save web page's source codes to any any text file and saving it C:\ folder.

I tried get web page's source with this code:

html = driver.page_source
print(html)

How to save page source to C:\ folder in a text file?

CodexSC
  • 31
  • 4

1 Answers1

2

Try this:

import urllib.request
site = urllib.request.urlopen('http://somesite.com')
data = site.read()
file = open("C:\\file.txt","wb") #open file in binary mode
file.writelines(data)
file.close()

or this

import urllib.request
def extractHTML(url):
    urllib.request.urlretrieve(url, 'C:\\file.txt')

See more details here

Prophet
  • 32,350
  • 22
  • 54
  • 79
  • Hello i need do this in selenium – CodexSC Sep 21 '21 at 21:19
  • You can do this as written in my answer and do all the rest with selenium. – Prophet Sep 21 '21 at 21:21
  • Hello, i did transfer your code but im getting this error: AttributeError: 'str' object has no attribute 'read'. How do i combine this with my code? – CodexSC Sep 21 '21 at 21:29
  • Are you sure you did this: `import urllib.request site = urllib.request.urlopen('http://somesite.com')` and not this: `html = driver.page_source` before applying `read()` method on it? – Prophet Sep 21 '21 at 21:33
  • Hello, yes i restored code but im getting this error: TypeError: a bytes-like object is required, not 'int'. Is there any way to do this without using urllib? Because im using my cookies and histories in webdriver. – CodexSC Sep 21 '21 at 21:40