【问题标题】:How to scrape web news and combine paragraphs into each article如何抓取网络新闻并将段落合并到每篇文章中
【发布时间】:2020-09-05 09:24:45
【问题描述】:

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

当我 print(myarticle[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/'))

【问题讨论】:

  • 你能把剩下的代码加进去,我们可以检查.. url等
  • 当然,我更新了描述。请检查:)
  • 什么是 clear_output 和 warn.. 它们来自哪里?
  • 我收到一条错误消息“超出最大重试次数”; clear_output 和警告。是为了解决这个问题。稍后我会抓取更多页面,clear_output 和 warn 可能会有所帮助。但是 clear_output 和 warn 与这个问题无关,你可以忽略它们:)

标签: python web-scraping beautifulsoup request web-crawler


【解决方案1】:

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

    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())

【讨论】:

  • 嗨 Niels,如果我使用你的方法,你知道为什么 myarticle 的长度是 100 吗?应该是 10。
  • 是的,你循环容器(可能 10 个)然后循环页面链接(可能还有 10 个),这意味着它将 10 次遍历 10 个页面链接。研究逐步调试并了解如何分析代码的作用。
  • 简化代码对我有用。但较长的版本似乎不起作用。我需要使用更长的版本,因为在另一个网站上我正在抓取“条目内容”包含不相关的元素,我需要在“条目内容”下找到“p”。我试图调试它,但我不能这样做。您能否检查一下代码中的哪个步骤有误(在应该类似的情况下)?如果我使用该代码,它会返回 [None] [None, None] [None, None, None]
  • 较长的版本只是为了表明如果您想在循环中重复使用列表,则需要清除列表。为什么你得到 None 可能是因为它找到的任何元素 P 都没有文本。如果没有“另一个”网站,这很难说。我再次敦促您学习逐步调试,这样您就可以在代码运行时看到站点和代码,变量的值彼此相邻。
  • 似乎 append() 没有返回它的值,更新了更长的代码。
猜你喜欢
  • 2022-08-10
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多