【问题标题】:BeautifulSoup Python saving Output links to txt fileBeautifulSoup Python将输出链接保存到txt文件
【发布时间】:2014-09-15 22:01:16
【问题描述】:

我正在尝试使用 BeautifulSoup 从网页中收集链接。到目前为止,我已经能够做到这一点,并使用当前从代码中注释掉的打印命令在命令提示符下将它们打印出来。我遇到的问题是当链接保存到 Output.txt 文件时,它们都相互覆盖,只保存最后一个链接。非常感谢任何帮助!

如果您对在一个程序中完成此转换有任何建议,请参阅我的最终目标。 我的最终目标是搜索 txt 文件中的链接,以确定其中是否包含特定文本。如果有,我想返回“Broken Link”或“Not Broken”。

soup = BeautifulSoup(html_doc) #html doc is source code for website i am using

for link in soup.find_all(rel="bookmark"):
  Gamma =(link.get('href'))
  f =open('Output.txt','w')
  f.write(Gamma)
  f.close()
  #print(Gamma)

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    你需要在循环之前打开文件进行写入,并在里面调用write()

    soup = BeautifulSoup(html_doc)
    
    with open('Output.txt','w') as f:
        for link in soup.find_all(rel="bookmark"):
            f.write(link.get('href'))
    

    另外,请注意,使用with context manager 有助于不必担心手动关闭文件。

    【讨论】:

      【解决方案2】:

      只需将“w”替换为“a”即可使其成为“附加”模式。

      soup = BeautifulSoup(html_doc) #html doc is source code for website i am using
      
      for link in soup.find_all(rel="bookmark"):
        Gamma =(link.get('href'))
        f =open('Output.txt','a')
        f.write("{gamma}\n".format(gamma=Gamma))
        f.close()
        #print(Gamma)`enter code here`
      

      【讨论】:

      • 这是一个的想法。像这样在循环中打开和关闭文件会增加 很多 不必要的开销。
      【解决方案3】:

      正如其他人所说,您需要附加文件。进行单次打开和关闭也更有效。

      f = open ('Output.txt', 'a')
      for link in soup.find_all(rel="bookmark")
         Gamma =(link.get('href')
         f.write(Gamma + '\n')
      f.close()
      

      【讨论】:

        猜你喜欢
        • 2016-07-02
        • 2016-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-14
        相关资源
        最近更新 更多