python 爬取图片 并保存至docx

#!/usr/bin/evn python
# -*- coding: utf-8 -*-

import os
import time

import requests
from docx import Document
from docx.shared import Inches


class MyObject(object):
    def __init__(self):
        self.doc = Document()

    def get_url(self, id):
        response = requests.get('http://***/img/pict-%d.png' % id)
        pic_dic = "%s.jpg" % str(id)
        with open(pic_dic, "wb")as f:
            f.write(response.content)
        self.doc.add_picture(pic_dic, width=Inches(6))  # 添加图, 设置宽度

        os.remove(pic_dic)

    def main(self):
        for id in range(1, 42):
            self.get_url(id)
        self.doc.save('XXX.docx')


if __name__ == '__main__':
    t0 = time.time()

    mo = MyObject()
    mo.main()

    print("耗时:", time.time() - t0)

不知道如何直接保存爬取的图片到docx,只能先保存图片,在保存到docx,再删除图片。
doc.add_picture(pic_dic)

安装: pip install python-docx

 

### Python 爬虫抓取网页图文内容保存DOCX 文件 为了实现从网页上抓取图文内容将这些内容保存到 `.docx` 文档中,通常需要以下几个步骤: #### 使用 `requests` 和 `BeautifulSoup` 获取网页数据 首先,利用 `requests` 库来获取目标网站的数据流。接着通过 `BeautifulSoup` 解析 HTML 页面结构,提取所需的文字和图像链接。 ```python import requests from bs4 import BeautifulSoup url = 'http://example.com' # 替换成实际网址 response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') ``` #### 下载图片资源 对于页面中的每一张图片,可以通过其 URL 进行下载操作,将其存储至本地文件夹内以便后续处理[^1]。 ```python images_folder = './images/' os.makedirs(images_folder, exist_ok=True) for img_tag in soup.find_all('img'): src = img_tag['src'] filename = os.path.join(images_folder, os.path.basename(src)) with open(filename, mode='wb') as f: image_data = requests.get(src).content f.write(image_data) ``` #### 创建 Word 文档对象 引入 `python-docx` 来创建一个新的 Word (.docx) 文件实例,在其中添加段落、表格以及插入之前所下载好的图片等元素[^3]。 ```python from docx import Document from docx.shared import Inches document = Document() ``` #### 向文档中添加文字与图片 遍历解析后的 HTML 结构,依次向文档里追加相应的文本节点;当遇到 `<img>` 标签时,则读取对应的本地路径下的二进制数据作为插图加入到当前段落后方[^2]。 ```python for element in soup.body.descendants: if isinstance(element, str): # 处理纯文本部分 document.add_paragraph(element.strip()) elif element.name == 'p': # 对于 <p> 段落标签特别对待 p = document.add_paragraph('') for child in element.children: if hasattr(child, 'name') and child.name == 'img': try: rel_path = images_folder + os.path.basename(child['src']) p.add_run().add_picture(rel_path, width=Inches(1.25)) except Exception as e: print(f"Failed to add picture {rel_path}: ", e) elif isinstance(child, NavigableString): run = p.add_run(str(child)) # 最终保存整个 word 文档 output_filename = "./output.docx" document.save(output_filename) print(f'Document saved at {output_filename}') ``` 上述代码片段展示了如何使用 Python 编程语言结合第三方库完成网络爬虫的任务——即自动化的访问指定站点收集公开可用的信息资料,按照一定格式整理成易于阅读的形式输出给用户查看或进一步分析。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值