【网络安全带你练爬虫-100练】第20练:数据处理-并写入到指定文档位置

news/2024/7/19 12:36:24 标签: 爬虫, web安全, python

目录

一、目标1:解码+去标签

二、目标2:提取标签内内容

三、目标3:处理后的数据插入原位置

四、目标4:将指定的内容插入指定的位置

五、目标5:设置上下文字体格式

六、目标6:向多个不同位置插入不同的字符串

七、目标7:向多个不同位置插入不同的字符串

八、目标8:图文写入到指定的字符串后面


一、目标1:解码+去标签

使用函数:html.unescape()解码+replace()替换

python">import html

data = '\u003cp\u003e(此处忽略一万个字)'

# 解码HTML实体,并替换相应字符
decoded_data = html.unescape(data).replace('<p><br></p>', '\n').replace('<p>','').replace('</p>','')


# 输出结果
print(decoded_data)



二、目标2:提取标签内内容

思路:其实也就是正则匹配

img标签去掉并换行,只留下URL

代码:

python">import re

text = '<img src="URL">…………(此处省略一万字)'

# 提取URL
urls = re.findall(r'<img\s+src="([^"]+)"\s*>', text)

# 替换<img>标签为URL,并添加换行符
for url in urls:
    text = re.sub(r'<img\s+src="[^"]+"\s*>', url + '\n', text, count=1)

print(text)



三、目标3:处理后的数据插入原位置

将以下代码中图片URL下载后,并按照原位置插入文档

python">import requests
from docx import Document
from docx.shared import Inches

# 创建一个新的Word文档
doc = Document()

text = '''
图片:
https://xxxxx.png
'''

# 以换行符分割文本
lines = text.split('\n')

for line in lines:
    if line.startswith('https://'):
        # 下载图片
        response = requests.get(line)
        image_path = line.split('/')[-1]  # 使用URL中的最后一部分作为文件名保存图片
        with open(image_path, 'wb') as f:
            f.write(response.content)
        
        # 插入图片到Word文档
        doc.add_picture(image_path, width=Inches(4))  # 根据需要调整图片的宽度
    else:
        # 插入文本到Word文档
        doc.add_paragraph(line)

# 保存Word文档
doc.save("output.docx")

四、目标4:将指定的内容插入指定的位置

使用python打开一个word文档,并将内容写入到指定字符串后面

python">from docx import Document

# 打开Word文档
doc = Document('example.docx')

# 获取文档中所有段落的内容
paragraphs = [p.text for p in doc.paragraphs]

# 指定要插入内容的位置
target_string = '指定字符串'
insert_index = paragraphs.index(target_string) + 1  # 在目标字符串后面插入,所以需要加1

# 要插入的内容
new_content = '要插入的内容'

# 在指定位置后插入内容
doc.paragraphs[insert_index].insert_paragraph_before(new_content)

# 保存修改后的Word文档
doc.save('example_modified.docx')



五、目标5:设置上下文字体格式

将写入文本的的字体大小与上一行一致

python">from docx import Document
from docx.shared import Pt

# 打开Word文档
doc = Document('example.docx')

# 获取上一行的字体大小
previous_paragraph = doc.paragraphs[-1]
previous_run = previous_paragraph.runs[-1]
previous_font_size = previous_run.font.size

# 要写入的文本内容
new_text = '新的文本'

# 在新行中写入文本
new_paragraph = doc.add_paragraph()
new_run = new_paragraph.add_run(new_text)

# 设置新行的字体大小与上一行一致
new_font = new_run.font
new_font.size = previous_font_size

# 保存修改后的Word文档
doc.save('example_modified.docx')

插入与上一行字体一样大小的文字

python">from docx import Document
from docx.shared import Pt

def word_info_w():
    # 打开Word文档
    doc = Document('test.docx')

    # 获取文档中所有段落的内容
    paragraphs = [p.text for p in doc.paragraphs]

    # 指定要插入内容的位置
    target_string = '附件:'
    insert_index = paragraphs.index(target_string) + 1  # 在目标字符串后面插入,所以需要加1

    # 获取上一行的字体大小
    previous_paragraph = doc.paragraphs[insert_index - 1]
    previous_run = previous_paragraph.runs[-1]
    previous_font_size = previous_run.font.size

    # 要插入的内容
    new_content = '测试title'

    # 在指定位置后插入内容
    new_paragraph = doc.paragraphs[insert_index].insert_paragraph_before(new_content)

    # 设置新插入内容的字体大小与上一行一致
    new_run = new_paragraph.runs[0]
    new_font = new_run.font
    new_font.size = previous_font_size

    # 保存修改后的Word文档
    doc.save('test.docx')

if __name__ == '__main__':
    word_info_w()



六、目标6:向多个不同位置插入不同的字符串

向多个不同位置插入不同的字符串

(可能会插入到同一个位置)

python">from docx import Document

def insert_content(doc, insert_dict):
    # 获取文档中所有段落的内容
    paragraphs = [p.text for p in doc.paragraphs]

    for target_string, new_content in insert_dict.items():
        if target_string in paragraphs:
            # 指定要插入内容的位置
            insert_index = paragraphs.index(target_string) + 1  # 在目标字符串后面插入,所以需要加1

            # 获取上一行的字体大小
            previous_paragraph = doc.paragraphs[insert_index - 1]
            previous_run = previous_paragraph.runs[-1]
            previous_font_size = previous_run.font.size

            # 在指定位置后插入内容
            new_paragraph = doc.paragraphs[insert_index].insert_paragraph_before(new_content)

            # 设置新插入内容的字体大小与上一行一致
            new_run = new_paragraph.runs[0]
            new_font = new_run.font
            new_font.size = previous_font_size

    # 保存修改后的Word文档
    doc.save('test.docx')

if __name__ == '__main__':
    # 打开Word文档
    doc = Document('test.docx')

    # 定义要插入的内容和位置的字典
    insert_dict = {
        '附件:': '测试title1',
        '目录:': '测试title2'
    }

    # 插入内容
    insert_content(doc, insert_dict)



七、目标7:向多个不同位置插入不同的字符串

python">from docx import Document

def insert_content(doc, target_string, new_content):
    # 获取文档中所有段落的内容
    paragraphs = [p.text for p in doc.paragraphs]

    if target_string in paragraphs:
        # 指定要插入内容的位置
        insert_index = paragraphs.index(target_string) + 1  # 在目标字符串后面插入,所以需要加1

        if insert_index < len(doc.paragraphs):
            # 在指定位置后插入内容
            doc.paragraphs[insert_index].insert_paragraph_before(new_content)

    # 保存修改后的 Word 文档
    doc.save('test.docx')

if __name__ == '__main__':
    # 打开 Word 文档
    doc = Document('test.docx')

    # 定义要插入的内容和位置的字典
    insert_dict = {
        '指定字符1位置': '插入内容1',
        '指定字符2位置': '插入内容2',
        '指定字符3位置': '插入内容3'
    }

    for target_string, new_content in insert_dict.items():
        # 插入内容
        insert_content(doc, target_string, new_content)

指定字体大小

python">from docx import Document
from docx.shared import Pt

def insert_content(doc, target_string, new_content):
    # 获取文档中所有段落的内容
    paragraphs = [p.text for p in doc.paragraphs]

    if target_string in paragraphs:
        # 指定要插入内容的位置
        insert_index = paragraphs.index(target_string) + 1  # 在目标字符串后面插入,所以需要加1

        if insert_index < len(doc.paragraphs):
            # 在指定位置后插入内容
            paragraph = doc.paragraphs[insert_index]
            run = paragraph.insert_paragraph_before(new_content).runs[0]
            font = run.font
            font.size = Pt(12)  # 设置字体大小为3号字体(12磅)

    # 保存修改后的 Word 文档
    doc.save('test.docx')

if __name__ == '__main__':
    # 打开 Word 文档
    doc = Document('test.docx')

    # 定义要插入的内容和位置的字典
    insert_dict = {
        '指定字符1位置': '插入内容1',
        '指定字符2位置': '插入内容2',
        '指定字符3位置': '插入内容3'
    }

    for target_string, new_content in insert_dict.items():
        # 插入内容
        insert_content(doc, target_string, new_content)



八、目标8:图文写入到指定的字符串后面

python">from docx import Document
from docx.shared import Pt
from docx.shared import Inches
import requests

def word_img_text_w(word, target_string):
    # 打开 Word 文档
    doc = Document('test.docx')

    # 获取文档中所有段落的内容
    paragraphs = [p.text for p in doc.paragraphs]

    if target_string in paragraphs:
        # 指定目标字符串的位置
        insert_index = paragraphs.index(target_string) + 1  # 在目标字符串后面插入,所以需要加1

        # 以换行符分割文本
        lines = word.split('\n')

        for line in lines:
            if line.startswith('https://'):
                # 下载图片
                response = requests.get(line)
                image_path = line.split('/')[-1]  # 图片保存的本地路径,使用URL中的最后一部分作为文件名
                with open(image_path, 'wb') as f:
                    f.write(response.content)
                # 插入图片到Word文档
                doc.paragraphs[insert_index].add_run().add_picture(image_path, width=Inches(4))  # 根据需要调整图片的宽度
                insert_index += 1
            else:
                # 插入文本到Word文档
                run = doc.paragraphs[insert_index].add_run(line)
                run.font.size = Pt(16)  # 设置字体大小为16磅
                insert_index += 1

    # 保存Word文档
    doc.save("test.docx")

if __name__ == '__main__':
    # 要插入的内容
    content = '''测试
https://xx.png
https://xxxx.png'''

    # 指定目标字符串
    target_string = '指定目标字符1'

    # 插入内容到Word文档
    word_img_text_w(content, target_string)


http://www.niftyadmin.cn/n/5002471.html

相关文章

MySql学习笔记02——MySql的简单介绍

MySQL 常用命令 注意在mysql中使用的命令需要用英文分号结尾&#xff08;启动/关闭mysql服务不需要带分号&#xff09; net start mysql 启动mysql服务&#xff08;需要管理员启动cmd&#xff09; net stop mysql关闭mysql服务&#xff08;需要管理员启动cmd&#xff09; m…

SpringBoot实现分页的四种方式

一 自己封装Page对象实现 博客链接 二 使用sql实现分页 2.1 场景分析 前段传递给给后台什么参数? 当前页码currentPage每页显示条数pageSize 后台给前端返回什么数据? 当前页数据List总记录数totalCount 2.2 前段代码 <template><el-paginationsize-change&q…

互联网医院|医疗系统新模式改善看病效率

伴随着互联网时代的进步&#xff0c;医疗也在不断的发展&#xff0c;越来越多的医院和诊所开始使用医疗软件。医疗软件广泛的被使用着&#xff0c;软件几乎覆盖了我们的日常生活。在我们日常生活当中健康一直是需求专业渠道&#xff0c;医疗软件开发会把用户的数据打造出一个数…

强化学习算法总结 2

强化学习算法总结 2 4.动态规划 待解决问题分解成若干个子问题&#xff0c;先求解子问题&#xff0c;然后得到目标问题的解 需要知道整个状态转移函数和价值函数&#xff0c;状态空间离散且有限 策略迭代&#xff1a; 策略评估:贝尔曼期望方程来得到一个策略的 V ( s ) V(s…

01-数据类型和转换

数据 定义&#xff1a;对现实生活中事物的抽象描述&#xff0c;在程序世界中一切都采用数据进行描述&#xff0c;程序的执行实际上就是对数据的操作。数据是存储在内存和硬盘中的。 数据类型 基本数据类型&#xff1a; 数字&#xff08;number)、字符串&#xff08;string&…

泛微OA流程表单中代码块获取URL的参数

获取URL的参数 需要编辑自定义函数 function getUrlParam(key){var url decodeURI(window.location.href);var paramMap {};var paramStr url.split("?")[2];if (paramStr && paramStr ! "") {var paramStrArr paramStr.split("&&qu…

爱校对:让法律、医疗、教育行业的文本更加无懈可击

在今天这个信息爆炸的世界里&#xff0c;文本准确性成了法律、医疗和教育这些严谨行业中一个不能忽视的要点。一个小错误可能造成严重的后果&#xff0c;甚至影响人们的生命和事业。这正是为什么更多的专业人士开始选择使用“爱校对”来确保他们的文档、研究和通讯无懈可击。 法…

高等数学笔记

|sinx|连续不可导 只要在x0处存在极限且极限等于f(x0)则函数在此处连续 如果某点可导则左右导数应该相等&#xff08;可导一定连续&#xff0c;连续不一定可导&#xff09; 双曲函数的由来 塞入dx 莱布尼茨公式 sin(nx)的k次导n^k*sin(nxkΠ/2) 注意符号&#xff01; 二阶导公…