ไม่สามารถดึงเนื้อหาของบทความโดยใช้ beautifulsoup ใน python 3.7

ฉันกำลังขูดเว็บโดยใช้ beautifulsoup ใน python 3.7 โค้ดด้านล่างคัดลอกวันที่ ชื่อ แท็กได้สำเร็จ แต่ไม่ใช่เนื้อหาของบทความ มันคือการไม่มีให้แทน

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