我是一个学习网络爬虫的初学者,由于某种原因,我无法爬网this网站。当我在Chrome中检查代码时,代码看起来不错,但是当我使用BeautifulSoup读取代码时,该代码就不再可抓取。汤中提到“ Google Analytics(分析)”,我真的不知道那是什么。
答案 0 :(得分:1)
该站点的内容是通过JavaScript加载的,但是您可以使用requests
模块来获取各个章节。章节的URL格式为https://detroitbecometext.github.io/assets/html/chapterXY.html
(example)。
例如此脚本:
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)
打印所有章节的所有文本:
...
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!
...