Skip to content
Advertisement

Python3. How to save downloaded webpages to a specified dir?

I am trying to save all the < a > links within the python homepage into a folder named ‘Downloaded pages’. However after 2 iterations through the for loop I receive the following error:

www.python.org#content <_io.BufferedWriter name=’Downloaded Pages/www.python.org#content’> www.python.org#python-network <_io.BufferedWriter name=’Downloaded Pages/www.python.org#python-network’>

Traceback (most recent call last): File “/Users/Lucas/Python/AP book exercise/Web Scraping/linkVerification.py”, line 26, in downloadedPage = open(os.path.join(‘Downloaded Pages’, os.path.basename(linkUrlToOpen)), ‘wb’) IsADirectoryError: [Errno 21] Is a directory: ‘Downloaded Pages/’

I am unsure why this happens as it appears the pages are being saved as due to seeing ‘<_io.BufferedWriter name=’Downloaded Pages/www.python.org#content’>’, which says to me its the correct path.

This is my code:

JavaScript

Appreciate any advice, thanks.

Advertisement

Answer

The problem is that when you try to do things like parse the basename of a page with an .html dir it works, but when you try to do it with one that doesn’t specify it on the url like “http://python.org/” the basename is actually empty (you can try printing first the url and then the basename bewteen brackets or something to see what i mean). So to work arround that, the easiest solution would be to use absolue paths like @Thyebri said.

And also, remember that the file you write cannot contain characters like '/', '' or '?'

So, i dont know if the following code it’s messy or not, but using the re library i would do the following:

JavaScript

So, first i remove part i remove the "https://" part, and then with the regular expressions library i replace all the usual symbols that are present in url links with a dash '-' and that is the name that will be given to the file.

Hope it works!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement