BeautifulSoup img src gets base64 instead of actual link

Viewed 1065

I am new to web scraping using bs4 and I want to get the image of a protein from the Protein Data Bank (PDB):

https://www.rcsb.org/structure/1A69

When I inspect the HTML with Chrome Inspector I see that the image is sourced through a http link that I can easily go to and save the image from.

<img class="img-responsive center-block mainImage" 
     src="https://cdn.rcsb.org/images/rutgers/a6/1a69/1a69.pdb1-500.jpg">

However, when I run my script to extract the src, I only get it as base64.

data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=

Am I doing something wrong? What's happening? Is there a way to get the http link back from base64?

My code:

from bs4 import BeautifulSoup as bs
from urllib.request import urlopen

url = "https://www.rcsb.org/structure/1A69"
resp = urlopen(url)
page = bs(resp,"html.parser")

for img in page.findAll('img',{'class':'img-responsive'}):
    src = img['src']
    print(src)
2 Answers

The image URLs are composed dynamically by Javascript, but you can simulate the composing with this Python script:

import requests
from bs4 import BeautifulSoup

url = 'https://www.rcsb.org/structure/1A69'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
pdb_id = url.split('/')[-1].lower()
images_location = "https://cdn.rcsb.org/images/rutgers/"
num_items = len( soup.select('#carousel-structuregallery .item') )
pdb_hash = pdb_id[1:3]

# print image urls to screen:

for i in range(num_items):
    # 0 = Asymmetric; 1+ = Biological Assembly
    if i == 0:
        img_url = images_location + pdb_hash + '/' + pdb_id + '/' + pdb_id + '.pdb-500.jpg'
    else:
        img_url = images_location + pdb_hash + '/' + pdb_id + '/' + pdb_id + '.pdb' + str(i) + '-500.jpg'
    print(img_url)

Prints:

https://cdn.rcsb.org/images/rutgers/a6/1a69/1a69.pdb-500.jpg
https://cdn.rcsb.org/images/rutgers/a6/1a69/1a69.pdb1-500.jpg

If you want to see none-base64 images try this:

import requests as re
from bs4 import BeautifulSoup as bs
from urllib.request import urlopen
url = "https://www.rcsb.org/structure/1A69"
resp = urlopen(url)
soup = bs(resp, 'html.parser')
images = []

for img in soup.findAll('img'):
    images.append(img.get('src'))

for i in images:
    i = 'http:' + i
    try:
        response = re.get(i)
        if response.status_code == 200:
            print(i)
    except:
        continue

Output:

http://files.rcsb.org/pub/pdb/validation_reports/a6/1a69/1a69_multipercentile_validation.png
http://cdn.rcsb.org/rcsb-pdb/explorer/SSPv2/images/MendeleyIcon.png
http://cdn.rcsb.org/rcsb-pdb/explorer/SSPv2/images/EndNoteIcon.png
http://cdn.rcsb.org/images/ccd/unlabeled/F/FMB.svg
http://cdn.rcsb.org/images/ccd/unlabeled/S/SO4.svg
http://files.rcsb.org/pub/pdb/validation_reports/a6/1a69/1a69_multipercentile_validation.png
Related