【问题标题】:How to scrape data from a website and store in folders in a hierarchical stucture using python script?如何使用 python 脚本从网站上抓取数据并以分层结构存储在文件夹中?
【发布时间】:2019-07-11 20:27:01
【问题描述】:

我正在尝试使用 python 从网站获取数据,然后我已经在本地下载了文本文件,我想从文本文件中的锚标记获取数据,并将一个新文件夹重命名为锚标记值。

这里我正在使用 python 创建新文件夹,但无法从 txt 文件中获取数据并进行处理

我可以创建新文件夹,但我希望将重命名为锚标记值

import os

root_path = '/home'    
folders = ['folder 01', 'folder 02', 'folder 03']    
for folder in folders:
    os.mkdir(os.path.join(root_path, folder))

【问题讨论】:

  • 你能提供文本文件吗?你的预期输出应该是什么?例如,您要创建哪些文件夹?听起来您需要做的就是解析文本文件(我假设您的意思是 HTML ??)并将您想要的标签拉入列表中。然后,您可以将该列表用作循环的 folders 变量
  • 是的,该文件是一个 html 文件,直到现在我已经尝试获取一个文件并提取其中的锚标签,这就像 abccd 现在我想将此结果保存在一个数组中,以便我可以使用上面的代码重命名文件夹
  • 你的想法是对的。您需要使用 beautifulsoup 来解析 html ,找到您正在寻找的那些标签。你很可能会使用find_all(),但是如果没有看到实际的 html 是什么并具体确定如何找到这些标签,我不知道它的容量。

标签: python html beautifulsoup html-parsing


【解决方案1】:

请尝试下面的代码。它应该创建锚标记中存在的所有文件夹名称。

from bs4 import BeautifulSoup
import requests
import os
url = 'Url Here'
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
for folder in soup.find_all('a'):
    root_path = '/home'
    os.mkdir(os.path.join(root_path, folder.text))

如果这行得通,请告诉我。

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 2013-12-05
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多