首页 > 解决方案 > 将抓取的文本保存到不同的 txt 文件中

问题描述

我正在从不同的 URL 中抓取一些信息,并希望将每个信息保存到 .txt 中。首先,我得到了我需要的 URL 列表:

page = requests.get("https://www.imagino.com.br/gerador/listagem_senadores.php", headers={"User-Agent": "XY"})
sep = BeautifulSoup(page.content, 'html.parser')
links = [link.get('href') for link in sep.select('a')]

然后从这个 URL 列表中,我想从 class = "resumo" 中提取信息,并将每个信息保存在一个单独的 txt 文件中,该文件的名称包含在 class = "nome" 中:

for url in links:
    pg = requests.get(url)
    soup = BeautifulSoup(pg.content, 'html.parser')
    name = soup.find('div', class_ = 'nome').text
    res = soup.find('div', class_ = 'resumo').text
    with open("%s.txt" % \ (name), "a+") as f:
        for i in range(0, len(res)):
            print(res)
            f.write(res)

这将返回此错误:

File "<ipython-input-151-3aeb1e867f0f>", line 6
    with open("%s.txt" % \ (name), "a+") as f:
                                              ^
SyntaxError: unexpected character after line continuation character

我搜索了很多,找不到答案。你们能帮帮我吗?

标签: pythonweb-scrapingbeautifulsoup

解决方案


with open("%s.txt" % \ (name), "a+") as f:

去掉 "%" "\" 后的 "\" 指定换行符,基本上它为了可读性将单行代码分成两行。


推荐阅读