【问题标题】:python code to write extracted info to text filepython代码将提取的信息写入文本文件
【发布时间】:2020-10-25 12:27:46
【问题描述】:

我刚刚写了一个简单的python程序来从谷歌新闻中提取链接,这是成功的。我现在遇到的问题是我想将所有这些链接写入或附加到文本文件,但它只写入第一个链接而不是所有链接。我该如何实现?

我的代码如下所示

from urllib.request import urlopen
from bs4 import BeautifulSoup as Soup


class Scraper:
    def __init__(self, site):
        self.site = site

    def scrape(self):
        req = urlopen(self.site)
        html = req.read()
        parser = "html.parser"
        sp = Soup(html, parser)
        news_list = sp.find_all("a")
        for tag in news_list:
            url = tag.get("href")
            print("\n", url)
            print("-" * 110)
            with open("elder.txt", "w+") as f:
                f.write(str(url))

news = "https://news.google.com"
Scraper(news).scrape()

【问题讨论】:

    标签: python file append write


    【解决方案1】:

    您需要提前打开文件,而不是在每个 url 写入之前打开它。

    你目前只是打开一个新的文件,在你写之前清除它。

    with open("elder.txt", "w+") as f:
        for tag in news_list:
            url = tag.get("href")
            print("\n", url)
            print("-" * 110)
            f.write(str(url))
    

    或使用:open("elder.txt", "a") 在每次运行脚本时附加到文件。

    【讨论】:

      【解决方案2】:

      问题是您没有始终打开文件。在 for 循环中每次迭代都打开一次。

      在整个函数中保持打开状态,它会起作用。

      from urllib.request import urlopen
      from bs4 import BeautifulSoup as Soup
      
      
      class Scraper:
          def __init__(self, site):
              self.site = site
          def scrape(self):
              with open("elder.txt", "w+") as f:
                  req = urlopen(self.site)
                  html = req.read()
                  parser = "html.parser"
                  sp = Soup(html, parser)
                  news_list = sp.find_all("a")
                  for tag in news_list:
                      url = tag.get("href")
                      print("\n", url)
                      print("-" * 110)
                      f.write(str(url) + '\n')
      
      news = "https://news.google.com"
      links = Scraper(news).scrape()
      

      试试这个。

      【讨论】:

        【解决方案3】:

        您的代码中的问题是您在循环中打开了一个文件。这是什么意思?,当你用“w+”模式打开文件时,它会删除文件以前的数据(只需重写它)。顺便说一句,您使用了错误的模式,“w+”用于写入和读取(两者)。您需要使用“w”模式(仅写入)并将其放在循环之前,因为我们希望对所有循环过程使用相同的文件并写入您所理解的相同位置。

        你需要的代码:

        def scrape(self):
            req = urlopen(self.site)
            html = req.read()
            parser = "html.parser"
            sp = Soup(html, parser)
            news_list = sp.find_all("a")
            with open("elder.txt", "w") as f:
                for tag in news_list:
                    url = tag.get("href")
                    print("\n", url)
                    print("-" * 110)
        
                    f.write(str(url))
        

        【讨论】:

          猜你喜欢
          • 2021-06-04
          • 1970-01-01
          • 1970-01-01
          • 2013-05-31
          • 1970-01-01
          • 1970-01-01
          • 2017-10-24
          • 2012-07-15
          • 1970-01-01
          相关资源
          最近更新 更多