【问题标题】:BeautifulSoup cannot find all <p> tags in htmlBeautifulSoup 在 html 中找不到所有 <p> 标签
【发布时间】:2016-10-25 16:37:46
【问题描述】:

我正在尝试使用 BeautifulSoup 从网站中提取文章的标题、文本和用户 cmets。我已经设法过滤了前两个,但我在拉取用户 cmets 时遇到了问题。我现在有的代码。

def extract_text(url):
    url_to_extract = url
    html = urllib.urlopen(url_to_extract).read()
    soup = BeautifulSoup(html, 'html.parser')
    for script in soup(["script", "style"]):
        script.extract()
    print 'Title and Publisher is:\n' + soup.title.string
    body_text = ''
    article = soup.findAll('p')
    for element in article:
        body_text += '\n' + ''.join(element.findAll(text=True))
    print body_text

def main():
   url_title = 'https://www.theguardian.com/politics/2016/oct/24/nicola-sturgeon-says-brexit-meeting-was-deeply-frustrating'
   extract_text(url_title)

我已经在 main 方法中检查了这篇特定文章的源代码,用户 cmets 在

标记中可用,这应该使 BeautifulSoup 将它们与文章文本一起解析,但它没有显示。我试图通过

打印所有的beautifulsoup内容
print soup

它没有显示用户 cmets 应该在的 div。我现在已经在 BBC 和 Guardian 网站上尝试过。我很乐意在这里提供任何帮助。

【问题讨论】:

    标签: html python-2.7 beautifulsoup


    【解决方案1】:
    import requests
    from bs4 import BeautifulSoup
    
    def getArticle(url):
        url = 'http://www.bbc.com/news/business-34421804'
        result = requests.get(url)
        c = result.content
        soup = BeautifulSoup(c)
    
        article_text = ''
        article = soup.findAll('p')
        for element in article:
            article_text += '\n' + ''.join(element.findAll(text = True))
        return article_text
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多