Why is this website not scrape-able with bs4?

Viewed 317

I'm a beginner learning to webscrape, and for some reason I can't scrape this site. When I inspect it in Chrome, the code looks fine, but when I read it with BeautifulSoup it is no longer scrape-able. The soup mentions 'Google Analytics', I don't really know what that is.

1 Answers

The content of the site is loaded through JavaScript, but you can use requests module to get the individual chapters. The URL of chapters is in form https://detroitbecometext.github.io/assets/html/chapterXY.html (example).

For example this scrip:

import re
import requests
from bs4 import BeautifulSoup


url = 'https://detroitbecometext.github.io/chapters'
asset_url = 'https://detroitbecometext.github.io/assets/html/'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')
main_js = requests.get('https://detroitbecometext.github.io/' + soup.select_one('script[src^="main."]')['src']).text

for ch in re.findall(r'(chapter[\d.]+\.html?)', main_js):
    soup = BeautifulSoup(requests.get(asset_url + ch).content, 'html.parser')
    print(soup.get_text())
    print('-' * 80)

Prints all text from all chapters:

...


Out of the elevator

SWAT: Negotiator on site. Repeat, negotiator on site.
Caroline Phillips: No, stop... I... I... I can't leave her. Oh, oh please, please, you gotta save my little girl... Wait... you're
        sending an android?
SWAT: Alright, ma'am. We need to go.
Caroline Phillips: You can't...you can't do that! You W- Why aren't you sending a real
        person? Don't let that thing near her! Keep that thing away from my daughter! KEEP IT AWAY!
    

...
Related