Why is my python code (extract below) not decoding base64?

40 views Asked by At

first time poster and python novice here.

I'm writing a programme that finds images encoded in base64 and decodes them. At the moment, I'm able to find the required data in base64 encoded format from the website (Google Images) but I can't decode it within the programme. How can I fix it (code below) to get the decoded base64 data to print too?

Here's what I've tried - the bit of the code that's relevant to finding the base64 data and decoding it:

from bs4 import BeautifulSoup
import base64

for a in soup.findAll(attrs={'class': 'fR600b'}):
    name = a.find('img')
    code = name.get('src')
    if code is not None:
        code = code.replace('data:image/jpeg;base64,', '')
        code = code.replace('data:image/png;base64,', '')
        print(code)
        for c in code:
            try:
                decode = base64.b64decode(c)
                print(decode)

I'd expected this to print the encoded base64 data and, once decoded, to print the decoded base64 data. However, the decoded data is blank. Here's an extract from the code output - it prints the encoded data in full (I've abbreviated it here) but the corresponding decoded data is blank:

/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUSExMVFhUXGRYaGRcYGBoXGBgeGhcYGhgYGx0YHSggGBomHh etc.
b''
b''
/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUTEhMVFRUSFxcYGRgXFxgXGhcXGBUXFxUaGBUYHiggHRolGx etc. b''
b''

Grateful for your help and please let me know if there are other ways to improve the code too!

0

There are 0 answers