Не удается получить содержимое статей с помощью beautifulsoup в Python 3.7

Я занимаюсь веб-парсингом с помощью beautifulsoup в python 3.7. Приведенный ниже код успешно очищает дату, заголовок, теги, но не содержимое статей. Вместо этого он дает None.

import time
import requests
from bs4 import BeautifulSoup
from bs4.element import Tag
url = 'https://www.thehindu.com/search/?q=cybersecurity&order=DESC&sort=publishdate&ct=text&page={}'
pages = 32
for page in range(4, pages+1):
    res = requests.get(url.format(page))
    soup = BeautifulSoup(res.text,"lxml")
    for item in soup.find_all("a", {"class": "story-card75x1-text"}, href=True):
        _href = item.get("href")
        try:
            resp = requests.get(_href)
        except Exception as e:
            try:
                resp = requests.get("https://www.thehindu.com"+_href)
            except Exception as e:
                continue

        dateTag = soup.find("span", {"class": "dateline"})
        sauce = BeautifulSoup(resp.text,"lxml")
        tag = sauce.find("a", {"class": "section-name"})
        titleTag = sauce.find("h1", {"class": "title"})
        contentTag = sauce.find("div", {"class": "_yeti_done"})

        date = None
        tagName = None
        title = None
        content = None

        if isinstance(dateTag,Tag):
            date = dateTag.get_text().strip()

        if isinstance(tag,Tag):
            tagName = tag.get_text().strip()

        if isinstance(titleTag,Tag):
            title = titleTag.get_text().strip()

        if isinstance(contentTag,Tag):
            content = contentTag.get_text().strip()

        print(f'{date}\n {tagName}\n {title}\n {content}\n')

        time.sleep(3)

Я не понимаю, в чем проблема, поскольку я пишу правильный класс в contentTag.

Спасибо.


person Piyush Ghasiya    schedule 24.06.2019    source источник
comment
Еще раз проверьте источник страницы, которую читает ваш Beautiful Soup. Возможно, исходный код страницы даже не содержит обязательного тега.   -  person Argon    schedule 24.06.2019


Ответы (1)


Я предполагаю, что ссылки, по которым вы хотели бы перейти с первой страницы на ее внутреннюю, заканчиваются на .ece. Я применил эту логику в скрипте для обхода этих целевых страниц для очистки данных. Я определил селекторы для контента немного иначе. Теперь похоже, что он работает правильно. Следующий сценарий извлекает данные только со страницы 1. Не стесняйтесь изменять их в соответствии с вашими требованиями.

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

url = 'https://www.thehindu.com/search/?q=cybersecurity&order=DESC&sort=publishdate&ct=text&page=1'
base = "https://www.thehindu.com"

res = requests.get(url)
soup = BeautifulSoup(res.text,"lxml")
for item in soup.select(".story-card-news a[href$='.ece']"):
    resp = requests.get(urljoin(base,item.get("href")))
    sauce = BeautifulSoup(resp.text,"lxml")
    title = item.get_text(strip=True)
    content = ' '.join([item.get_text(strip=True) for item in sauce.select("[id^='content-body-'] p")])
    print(f'{title}\n {content}\n')
person SIM    schedule 24.06.2019