如何抓取网络新闻并将段落合并到每篇文章中

2023-12-14

我正在从该网站抓取新文章https://nypost.com/search/China+COVID-19/page/2/?orderby=relevance我使用 for 循环来获取每篇新闻文章的内容,但我无法组合每篇文章的段落。我的目标是将每篇文章存储在一个字符串中,所有字符串都应该存储在我的文章 list.

When I 打印(我的文章[0]),它给了我所有的文章。我希望它应该给我一篇文章。

任何帮助将不胜感激!

            for pagelink in pagelinks:
                #get page text
                page = requests.get(pagelink)
                #parse with BeautifulSoup
                soup = bs(page.text, 'lxml')
                containerr = soup.find("div", class_=['entry-content', 'entry-content-read-more'])
                articletext = containerr.find_all('p')
                for paragraph in articletext:
                    #get the text only
                    text = paragraph.get_text()
                    paragraphtext.append(text)
                    
                #combine all paragraphs into an article
                thearticle.append(paragraphtext)
            # join paragraphs to re-create the article 
            myarticle = [''.join(article) for article in thearticle]
    
    print(myarticle[0])

为了清楚起见,完整代码附在下面

def scrape(url):
    user_agent = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko'}
    request = 0
    urls = [f"{url}{x}" for x in range(1,2)]
    params = {
       "orderby": "relevance",
    }
    pagelinks = []
    title = []
    thearticle = []
    paragraphtext = []
    for page in urls:
        response = requests.get(url=page,
                                headers=user_agent,
                                params=params) 
        # controlling the crawl-rate
        start_time = time() 
        #pause the loop
        sleep(randint(8,15))
        #monitor the requests
        request += 1
        elapsed_time = time() - start_time
        print('Request:{}; Frequency: {} request/s'.format(request, request/elapsed_time))
        clear_output(wait = True)

        #throw a warning for non-200 status codes
        if response.status_code != 200:
            warn('Request: {}; Status code: {}'.format(request, response.status_code))

        #Break the loop if the number of requests is greater than expected
        if request > 72:
            warn('Number of request was greater than expected.')
            break


        #parse the content
        soup_page = bs(response.text, 'lxml') 
        #select all the articles for a single page
        containers = soup_page.findAll("li", {'class': 'article'})
        
        #scrape the links of the articles
        for i in containers:
            url = i.find('a')
            pagelinks.append(url.get('href'))
        #scrape the titles of the articles
        for i in containers:
            atitle = i.find(class_ = 'entry-heading').find('a')
            thetitle = atitle.get_text()
            title.append(thetitle)
            for pagelink in pagelinks:
                #get page text
                page = requests.get(pagelink)
                #parse with BeautifulSoup
                soup = bs(page.text, 'lxml')
                containerr = soup.find("div", class_=['entry-content', 'entry-content-read-more'])
                articletext = containerr.find_all('p')
                for paragraph in articletext:
                    #get the text only
                    text = paragraph.get_text()
                    paragraphtext.append(text)
                    
                #combine all paragraphs into an article
                thearticle.append(paragraphtext)
            # join paragraphs to re-create the article 
            myarticle = [''.join(article) for article in thearticle]
    
    print(myarticle[0])
print(scrape('https://nypost.com/search/China+COVID-19/page/'))

你不断地追加到现有的列表 [] 中,它不断增长,你需要在每个循环中清除它。

    articletext = containerr.find_all('p')
    for paragraph in articletext:
        #get the text only
        text = paragraph.get_text()
        paragraphtext.append(text)

    #combine all paragraphs into an article
    thearticle.append(paragraphtext)
# join paragraphs to re-create the article 
myarticle = [''.join(article) for article in thearticle]

应该是这样的

    articletext = containerr.find_all('p')
    thearticle = [] # clear from the previous loop
    paragraphtext = [] # clear from the previous loop
    for paragraph in articletext:
        #get the text only
        text = paragraph.get_text()
        paragraphtext.append(text)

    thearticle.append(paragraphtext)
    myarticle.append(thearticle)

但你可以将其进一步简化为:

article = soup.find("div", class_=['entry-content', 'entry-content-read-more'])
myarticle.append(article.get_text())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何抓取网络新闻并将段落合并到每篇文章中 的相关文章

随机推荐