10

使用puppeteer的type输入大段内容会造成乱码的解决方法

 2 years ago
source link: https://www.xiaosuiyin.com/2020/12/24/%e4%bd%bf%e7%94%a8puppeteer%e7%9a%84type%e8%be%93%e5%85%a5%e5%a4%a7%e6%ae%b5%e5%86%85%e5%ae%b9%e4%bc%9a%e9%80%a0%e6%88%90%e4%b9%b1%e7%a0%81%e7%9a%84%e8%a7%a3%e5%86%b3%e6%96%b9%e6%b3%95/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
使用puppeteer的type输入大段内容会造成乱码的解决方法 探索,发现,分享, 小碎银
> 编程笔记 > 使用puppeteer的type输入大段内容会造成乱码的解决方法

这两天我在做一个项目,其中一个环节需要用代向页面的某个textarea输入大段的文字。

这段文字的格式比较复杂,有很多html标签,很多的换行符在里面。

我立马想到的是puppeteertype方法。

但是当我用puppeteer的type方法自动输入内容的时候,发现它并不能很好的识别里面的换行符,会导致文字有很多的空格,格式错乱掉。

为了解决这个问题,在谷歌里搜索了很多次,也没有找到解决方法。

使用puppeteer的type输入大段内容会造成乱码的解决方法

就当我觉得这个问题无法解决的时候,发现了一个html的API,就是document.execCommand。

虽然这个API已经被废弃,但是还是可以用的!

不管黑猫白猫,抓到老鼠的就是好猫!

详细的内容可以看这里

果然啊,我把puppeteer的type方法替换成document.execCommand之后,粘贴进去的内容跟原来的格式一模一样!

使用puppeteer的type输入大段内容会造成乱码的解决方法

代码里的 insertText指的是在光标插入位置插入文本内容或者覆盖所选的文本内容

除了这个,还有insertHTML,insertImage,insertOrderedList等很多方法。



About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK