【问题标题】:Article scraping with beautifulsoup: scraping all <p> tags用 beautifulsoup 抓取文章:抓取所有 <p> 标签
【发布时间】:2014-09-20 10:01:22
【问题描述】:

我编写了一个脚本,它从文章中提取段落并将它们写入文件。对于某些文章,它不会拉动每一段。这就是我迷路的地方。任何指导将不胜感激。我已经包含了一个特定文章的链接,它没有提取所有信息。它会刮掉所有内容,直到第一个引用的句子。

网址:http://www.reuters.com/article/2014/03/06/us-syria-crisis-assad-insight-idUSBREA250SD20140306

# Ask user to enter URL
url = raw_input("Please enter a valid URL: ")

# Open txt document for output
txt = open('ctp_output.txt', 'w')

# Parse HTML of article
soup = BeautifulSoup(urllib2.urlopen(url).read())

# retrieve all of the paragraph tags
tags = soup('p')
for tag in tags:
    txt.write(tag.get_text() + '\n' + '\n')

【问题讨论】:

    标签: python html web-scraping html-parsing beautifulsoup


    【解决方案1】:

    这对我有用:

    import urllib2
    from bs4 import BeautifulSoup
    
    url = "http://www.reuters.com/article/2014/03/06/us-syria-crisis-assad-insight-idUSBREA250SD20140306"
    
    soup = BeautifulSoup(urllib2.urlopen(url))
    
    with open('ctp_output.txt', 'w') as f:
        for tag in soup.find_all('p'):
            f.write(tag.text.encode('utf-8') + '\n')
    

    请注意,您在处理文件时应该使用with 上下文管理器。您也可以将urllib2.urlopen(url) 直接传递给BeautifulSoup 构造函数,因为urlopen 返回一个类似文件的对象。

    希望对您有所帮助。

    【讨论】:

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