【问题标题】:Extract images from HTML file using python standard libraries使用 python 标准库从 HTML 文件中提取图像
【发布时间】:2017-06-09 20:57:45
【问题描述】:

所以我正在尝试编写一个基本上解析 HTML 文件的脚本,找到所有图像并将这些图像保存到另一个文件夹中。当您将它安装在计算机上时,如何仅使用 python3 附带的库来完成此操作?我目前有这个脚本,我想在其中加入更多内容。

date = datetime.date.today()
backup_path = os.path.join(str(date), language)
if not os.path.exists(backup_path):
    os.makedirs(backup_path)

log = []

endpoint = zendesk + '/api/v2/help_center/en-us/articles.json'
while endpoint:
    response = requests.get(endpoint, auth=credentials)
if response.status_code != 200:
    print('Failed to retrieve articles with error {}'.format(response.status_code))
    exit()
data = response.json()

for article in data['articles']:
    if article['body'] is None:
        continue
    title = '<h1>' + article['title'] + '</h1>'
    filename = '{id}.html'.format(id=article['id'])
    with open(os.path.join(backup_path, filename), mode='w', encoding='utf-8') as f:
        f.write(title + '\n' + article['body'])

    print('{id} copied!'.format(id=article['id']))

    log.append((filename, article['title'], article['author_id']))

endpoint = data['next_page']

这是我在 zendesk 论坛上找到的一个脚本,它基本上支持我们在 Zendesk 上的文章。

【问题讨论】:

  • 为什么不用美汤?
  • 看起来你没有分享完整的代码,但我想你想用urllib交换请求

标签: python html python-3.x


【解决方案1】:

尝试使用beautiful soup检索所有节点,并为每个节点使用urllib获取图片。

from bs4 import BeautifulSoup

#note here using response.text to get raw html
soup = BeautifulSoup(response.text)

#get the src of all images
img_source = [x.src for x in soup.find_all("img")]

#get the images
images = [urllib.urlretrieve(x) for x in img_source]

您可能需要添加一些错误处理并对其进行一些更改以适合您的页面,但想法保持不变。

【讨论】:

  • BeautifulSoup 和 urllib 随 Anaconda Python3 安装一起提供。
  • 那么也许使用 re 来提取 标签?不过,我不熟悉正则表达式,抱歉。
  • 感谢大家的回答!我试试看
猜你喜欢
  • 2018-08-05
  • 1970-01-01
  • 2021-08-30
  • 1970-01-01
  • 1970-01-01
  • 2010-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多