Not able to Scrape through BeautifulSoup

Viewed 89

I am trying to scrape image and news url from this website. The tag which i have defined is

root_tag=["div", {"class":"ngp_col ngp_col-bottom-gutter-2 ngp_col-md-6 ngp_col-lg-4"}]
image_tag=["div",{"class":"low-rez-image"},"url"]
news_url=["a",{"":""},"href"]

and url is url ,my code for scraping the website is.

ua1 = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
ua2 = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit 537.36 (KHTML, like Gecko) Chrome'
headers = {'User-Agent': ua2,
           'Accept': 'text/html,application/xhtml+xml,application/xml;' \
                     'q=0.9,image/webp,*/*;q=0.8'}
session = requests.Session()
response = session.get(url, headers=headers)
webContent = response.content
bs = BeautifulSoup(webContent, 'lxml')
all_tab_data = bs.findAll(root_tag[0], root_tag[1])

result=[]
for div in all_tab_data:
    try:
        news_url=None
        news_url = div.find(news_tag[0], news_tag[1]).get(news_tag[2])
        
    except Exception as e:
        news_url= None
    
    try:
        image_url = None
        div_img = str(div)
        match = re.search(r"(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png|jpeg)", div_img)
        if match != None:
            image_url = str(match.group(0))
        else:
            image_url = div.find(image_tag[0], image_tag[1]).get(image_tag[2])

    except Exception as e:
        image_url=None
        pass
    result.append([news_url,image_url])

I debug the code and find that all_tab_data is empty but i am choosing correct root_tag. So i dont know what i am doing wrong

2 Answers

The content is loaded from a JSON.

You can get all the image urls this way:

import requests

url = "https://www.nationalgeographic.com/magazine/_jcr_content/content/promo-carousel.promo-carousel.json"

data = requests.get(url).json()

for item in data:
    for sub_item in item['promo_carousel']:
        p_img = sub_item['promo_image']
        if p_img is not None:
            print(p_img['image']['uri'])

Output:

https://www.nationalgeographic.com/content/dam/animals/2020/09/african-cheetah-snow/african-cheetah-snow-2.jpg
https://www.nationalgeographic.com/content/dam/animals/2020/09/wallaby-atrazine/wallaby-og-a0xh8r-01.jpg
https://www.nationalgeographic.com/content/dam/animals/2020/09/elephant-tuberculosis/r40bfj.jpg
https://www.nationalgeographic.com/content/dam/animals/2020/08/handfish/01-handfish-minden_90392182.jpg
https://www.nationalgeographic.com/content/dam/science/2020/09/08/cal-fire-update/california-fire-palley-mm9468_200905_000229.jpg
https://www.nationalgeographic.com/content/dam/science/2020/09/11/face-mask-recognition/20200901_002_out_mp4_00_00_03_18_still003.jpg
https://www.nationalgeographic.com/content/dam/science/2020/09/10/winds-fires-california/winds-fires-california-2019.jpg
https://www.nationalgeographic.com/content/dam/science/2020/09/10/fire-air-quality/fire-air-pollution-20253854760329.jpg
https://www.nationalgeographic.com/content/dam/science/2020/09/02/autopsy/mm9412_200717_000522.jpg
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/departments/explore/stellar-map-milky-way-og.png
https://www.nationalgeographic.com/content/dam/science/2020/07/31/vaccine/vaccine_20209514426186.jpg
https://www.nationalgeographic.com/content/dam/archaeologyandhistory/rights-exempt/history-magazine/2020/09-10/metric-system/og-french-metric-system.jpg
https://www.nationalgeographic.com/content/dam/archaeologyandhistory/rights-exempt/OG/red-terror-explainer-og.jpg
https://www.nationalgeographic.com/content/dam/archaeologyandhistory/rights-exempt/OG/promo-medieval-pandemic.jpg
https://www.nationalgeographic.com/content/dam/archaeologyandhistory/2020/09/Asian-American-COVID/og_asianamerican.jpg
https://www.nationalgeographic.com/content/dam/archaeologyandhistory/2020/08/goodbye-hong-kong/19-hong-kong-security-law-china.jpg
https://www.nationalgeographic.com/content/dam/travel/commercial/2020/samsung/wyoming/samsung-wyoming-mountain.jpg
https://www.nationalgeographic.com/content/dam/travel/2020-digital/kissing-tourism-sites/gettyimages-3332297.jpg
https://www.nationalgeographic.com/content/dam/travel/2020-digital/thinking-about-traveling/nationalgeographic_1085186.jpg
https://www.nationalgeographic.com/content/dam/science/commercial/2019/domestic/wyss-foundation/wyss-foundation_cfn_natgeo-image-collection_1971120.jpg
https://www.nationalgeographic.com/content/dam/travel/2020-digital/least-visited-US-national-parks/nationalgeographic_2466315.jpg

EDIT: To get title and article data use this:

for item in data:
    for sub_item in item['promo_carousel']:
        print(f"{sub_item['components'][0]['title']['text']}"
              f"\n{sub_item['uri']}")
        p_img = sub_item['promo_image']
        if p_img is not None:
            print(f"{p_img['image']['uri']}")
        print("-" * len(sub_item['uri']))

Prints (shortened for brevity):

Rare photographs show African cheetahs in snowstorm
https://www.nationalgeographic.com/animals/2020/09/cheetahs-snow-south-africa/
https://www.nationalgeographic.com/content/dam/animals/2020/09/african-cheetah-snow/african-cheetah-snow-2.jpg
------------------------------------------------------------------------------
Wallabies exposed to common weed killer have reproductive abnormalities
https://www.nationalgeographic.com/animals/2020/09/wallaby-sexual-development-impaired-by-atrazine-herbicide/
https://www.nationalgeographic.com/content/dam/animals/2020/09/wallaby-atrazine/wallaby-og-a0xh8r-01.jpg
-------------------------------------------------------------------------------------------------------------
...

Another solution:

import json
import requests
from bs4 import BeautifulSoup

url = 'https://www.nationalgeographic.com/magazine/'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
data = json.loads( soup.select_one('[data-pestle-module="Lead"] [data-pestle-options]').string )

# to print all data uncomment next line:
# print(json.dumps(data, indent=4))

for b in data['body']:
    if 'multilayout_promo_beta' not in b:
        continue

    for s in b['multilayout_promo_beta']['stories']:
        if not s.get('lead_media'):
            continue
        if 'immersive_lead' not in s['lead_media']:
            print(s['components'][0]['title']['text'])
            print(s['lead_media']['image']['uri'])
        else:
            print(s['lead_media']['immersive_lead']['title'])
            print(s['lead_media']['immersive_lead']['lead_media']['image']['uri'])
        print(s['uri'])
        print('-' * 80)

Prints:

America’s neglected hiking trails are more popular than ever—but they’re struggling
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/us-hiking-trails/us-hiking-trails-campfire-valley.jpg
https://www.nationalgeographic.com/magazine/2020/10/america-long-neglected-hiking-trails-are-more-popular-than-ever-but-they-are-struggling-feature/
--------------------------------------------------------------------------------
The heroic effort in the Amazon to save one of the world’s largest eagles
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/saving-largest-eagle/harpy-eagles-brazil-14a.jpg
https://www.nationalgeographic.com/animals/2020/04/saving-worlds-largest-eagle/
--------------------------------------------------------------------------------
The robot revolution has arrived
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/09/rise-of-the-machines/mm8612_190408_00122-3.jpg
https://www.nationalgeographic.com/magazine/2020/09/the-robot-revolution-has-arrived-feature/
--------------------------------------------------------------------------------
They may look goofy, but ostriches are nobody’s fool
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/09/ostriches/ostriches-standing-tall-male-beach.jpg
https://www.nationalgeographic.com/magazine/2020/09/they-may-look-goofy-but-ostriches-are-nobodys-fool-feature/
--------------------------------------------------------------------------------
The Great Lakes depend on ice. This winter, they barely froze.
https://www.nationalgeographic.com/content/dam/science/2020/03/19/no-ice/year-with-no-ice-sacka-46.jpg
https://www.nationalgeographic.com/science/2020/03/great-lakes-depend-on-winter-ice-low-cover/
--------------------------------------------------------------------------------
‘I put my camera to my face and cried.’ Documenting a COVID-19 hot spot
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/departments/coronavirus/departements-detroit-singer-funeral.jpg
https://www.nationalgeographic.com/magazine/2020/10/danny-wilcox-frazier-on-photographing-covid-19-in-detroit/
--------------------------------------------------------------------------------
COVID-19’s impact on the animal kingdom—so far
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/departments/coronavirus/departments-covid-animals-tiger.jpg
https://www.nationalgeographic.com/magazine/2020/10/covid-19s-impact-on-the-animal-kingdom-so-far/
--------------------------------------------------------------------------------
To prevent the next deadly disease, we must stop harming nature
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/09/departments/coronavirus/departments-coronavirus-coral-reef.jpg
https://www.nationalgeographic.com/magazine/2020/09/pristine-seas-enric-sala-we-must-stop-harming-nature-to-prevent-deadly-disease-coronavirus/
--------------------------------------------------------------------------------
Beyond masks and gloves—here’s how the pros handle dangerous microbes
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/09/departments/coronavirus/tool-kit-covid-testing.jpg
https://www.nationalgeographic.com/magazine/2020/09/beyond-masks-and-gloves-here-is-how-the-pros-handle-dangerous-microbes/
--------------------------------------------------------------------------------
NASA sent a map to space to help aliens find Earth. Now it needs an update.
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/departments/explore/departments-stellar-map-galaxy.jpg
https://www.nationalgeographic.com/magazine/2020/10/nasa-sent-a-map-to-space-to-help-aliens-find-earth-now-it-needs-an-update/
--------------------------------------------------------------------------------
This archaeologist hunts DNA from prehistoric diseases
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/departments/coronavirus/departments-genius-rifkin.jpg
https://www.nationalgeographic.com/magazine/2020/10/archaeologist-riaan-rifkin-hunts-dna-from-prehistoric-diseases/
--------------------------------------------------------------------------------
See the ingenious cameras used to photograph elusive animals
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/10/departments/explore/departments-artifact-crittercam-wooden-fin.jpg
https://www.nationalgeographic.com/magazine/2020/10/see-the-ingenious-crittercams-used-to-photograph-elusive-animals/
--------------------------------------------------------------------------------
Popsicles and belly rubs: The joys of watching a panda grow up
https://www.nationalgeographic.com/content/dam/magazine/rights-exempt/2020/09/departments/explore/explore-essay-panda-stretching.jpg
https://www.nationalgeographic.com/magazine/2020/09/popsicles-and-belly-rubs-the-joys-of-watching-panda-bei-bei-grow-up/
--------------------------------------------------------------------------------
Related