Не удается получить содержимое статей с использованием Beautifulsoup в Python 3.7 - PullRequest
0 голосов
/ 24 июня 2019

Я занимаюсь веб-скребком с использованием 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.

Спасибо.

1 Ответ

1 голос
/ 24 июня 2019

Полагаю, что ссылки, которые вы хотели бы перейти с первой страницы до ее внутренней страницы, заканчиваются на .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')
...