Как очистить веб-контент с помощью BeautifulSoup, если в тексте ответа отсутствует весь контент, отображаемый в моем браузере? - PullRequest
0 голосов
/ 13 октября 2019

Используя JupyterNotebook (ipynb), я пытаюсь очистить веб-контент с помощью BeautifulSoup, но текст ответа содержит не весь контент, который отображается в моем браузере. Я пытаюсь получить заголовки статей и текст абзаца, но не могу получить текст абзаца, потому что он не отображается в моем браузере.

url = https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest

Я зашёл по URL в своем браузере и увидел содержимое, которое искал:

<div class="article_teaser_body">New evidence suggests salty, shallow ponds once dotted a Martian crater — a sign of the planet's drying climate.</div>

Однако, когда я печатал текст ответа, я не вижусодержание там.

from bs4 import BeautifulSoup
import requests
import os

url = 'https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest'

response = requests.get(url)

soup = BeautifulSoup(response.text, 'lxml')

title = soup.find_all('div', class_='content_title')

# This outputs exactly what I need but when I try to do it 
# for the paragraph text (see below code), in outputs an empty list.

results = soup.find_all('div', class_='article_teaser_body')

Список результатов пуст

1 Ответ

0 голосов
/ 13 октября 2019

Вам не нужно использовать красивый суп для очистки этого URL.

https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest

Когда я проверял вкладку сети, я обнаружил, что эта страница на самом деле получает тело статьи, используя JSON, полученный из запроса API, которыйможет быть легко сделано с помощью библиотеки requests.

Вы можете попробовать следующий код

import requests
import json # need to use this to pretty print json easily 

headers = {
  'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0' # to mimic regular browser user-agent
}

params = (
    ('page', '0'),
    ('per_page', '40'), # you tweak this value to 1000 or maybe more to get more data from a single request
    ('order', 'publish_date desc,created_at desc'),
    ('search', ''),
    ('category', '19,165,184,204'),
    ('blank_scope', 'Latest'),
)

# params is equivalent to page=1&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest

r = requests.get('https://mars.nasa.gov/api/v1/news_items/', params=params, headers=headers).json()

print(json.dumps(r, indent=4)) # prints the raw json respone

'''
The article data is contained inside the key `"items"`, we can iterate over `"items"` and 
print article title and body. Do check the raw json response to find 
other data included along with article title and body. You just need 
to use the key name to get those values like you see in the below code. 
'''

for article in r["items"]:
  print("Title :", article["title"])
  print("Body :",article["body"])

Смотрите это в действии здесь .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...