无法在python 3.7中使用beautifulsoup获取文章的内容

时间:2019-06-24 04:16:36

标签: web-scraping beautifulsoup python-3.7

我正在使用python 3.7中的beautifulsoup进行网络抓取。下面的代码成功地抓取了日期,标题,标签,但不是文章的内容。相反,它没有给出。

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 个答案:

答案 0 :(得分: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')