【问题标题】:Loop through list of URLs, run BeautifulSoup, write to file遍历 URL 列表,运行 BeautifulSoup,写入文件
【发布时间】:2017-03-08 16:19:05
【问题描述】:

我有一个要运行的 URL 列表,使用 BeautifulSoup 清理并保存到 .txt 文件。

这是我现在的代码,列表中只有几个项目,还有更多来自 txt 文件的项目,但现在这让它变得简单。

当循环工作时,它将两个 URL 的输出传递给 URL.txt 文件。我希望列表中的每个实例都输出到其唯一的 .txt 文件中。

import urllib
from bs4 import BeautifulSoup


x = ["https://www.sec.gov/Archives/edgar/data/1000298/0001047469-13-002555.txt",
"https://www.sec.gov/Archives/edgar/data/1001082/0001104659-13-011967.txt"]

for url in x:

    #I want to open the URL listed in my list

    fp = urllib.request.urlopen(url)
    test = fp.read()
    soup = BeautifulSoup(test,"lxml")
    output=soup.get_text()

    #and then save the get_text() results to a unique file.

    file=open("url.txt","w",encoding='utf-8')
    file.write(output)
    file.close()

感谢您观看。最好的,乔治

【问题讨论】:

  • 你能做到for i,url in enumerate(x): 并使用i 来构建url 文件名吗?
  • 我同意!下面的解释很好。

标签: python for-loop writefile


【解决方案1】:

为列表中的每个项目创建不同的文件名,如下所示:

import urllib
from bs4 import BeautifulSoup


x = ["https://www.sec.gov/Archives/edgar/data/1000298/0001047469-13-002555.txt",
"https://www.sec.gov/Archives/edgar/data/1001082/0001104659-13-011967.txt"]

for index , url in enumerate(x):

    #I want to open the URL listed in my list

    fp = urllib.request.urlopen(url)
    test = fp.read()
    soup = BeautifulSoup(test,"lxml")
    output=soup.get_text()

    #and then save the get_text() results to a unique file.

    file=open("url%s.txt" % index,"w",encoding='utf-8')
    file.write(output)
    file.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多