首页 > 解决方案 > 如何修复从网站解析正文的python代码?

问题描述

我正在尝试制作一个程序来解析该新闻网站档案每一页上每篇文章的正文。最初,我的程序在第 32 行停止,我打印了每个链接并将它们保存到一个 csv 文件中,这很有效。现在我想打开每个链接并将文章的正文保存到 csv 文件中。在使用 BeautifulSoup 方面,我尝试使用与最初相同的代码格式,但现在我的代码不打印任何内容。我不知道我的问题是我如何使用 BeautifulSoup 还是我如何从网站的 HTML 中编写标签。这是存档网站:https ://www.politico.com/newsletters/playbook/archive (上面有 408 页)

from bs4 import BeautifulSoup
from urllib.request import urlopen

csvFile = 'C:/Users/k/Dropbox/Politico/pol.csv'
with open(csvFile, mode='w') as pol:
    csvwriter = csv.writer(pol, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    #for each page on Politico archive
    for p in range(0,409):
        url = urlopen("https://www.politico.com/newsletters/playbook/archive/%d" % p)
        content = url.read()

        #Parse article links from page
        soup = BeautifulSoup(content,"lxml")
        articleLinks = soup.findAll('article', attrs={'class':'story-frag format-l'})

        #Each article link on page
        for article in articleLinks:
            link = article.find('a', attrs={'target':'_top'}).get('href')

            #Open and read each article link
            articleURL = urlopen(link)
            articleContent = articleURL.read()

            #Parse body text from article page
            soupArticle = BeautifulSoup(articleContent, "lxml")

            #Limits to div class = story-text tag (where article text is)
            articleText = soup.findAll('div', attrs={'class':'story-text'})
            for div in articleText:
                #Limits to b tag (where the body text seems so exclusively be)
                bodyText = div.find('b')
                print(bodyText)

                #Adds article link to csv file
                csvwriter.writerow([bodyText]) 

我希望输出打印存档中每篇文章的正文并将其全部保存到 csv 文件中。

标签: pythonhtmlparsingbeautifulsoup

解决方案


它没有打印任何内容,因为您在错误的位置查看articleText = soup.findAll('div', attrs={'class':'story-text'})

您将其存储为soupArticle,而不是soup

您还想要文本还是 html 元素?照原样,您将获得标签/元素。如果你只想要文本,你需要bodyText = div.find('b').text

但主要问题是你想改变:

articleText = soup.findAll('div', attrs={'class':'story-text'})

articleText = soupArticle.findAll('div', attrs={'class':'story-text'})

要获得完整的文章,您必须遍历p标签。并弄清楚如何跳过你不想要的部分。有一种更好的方法,但为了让你继续前进,如下所示:

for article in articleLinks:
    link = article.find('a', attrs={'target':'_top'}).get('href')

     articleURL = urlopen(link)
     articleContent = articleURL.read()

     soupArticle = BeautifulSoup(articleContent, "lxml")
     articleText = soupArticle.findAll('div', attrs={'class':'story-text'})

     for div in articleText:
        bodyText = div.find_all('p')
        for para in bodyText:
            if 'By ' in para.text:
                continue
            print (para.text.strip())

推荐阅读