鱼C论坛

 找回密码
 立即注册
查看: 1770|回复: 2

[已解决]关于 BeautifulSoup 对象的.prettify() 方法

[复制链接]
发表于 2021-7-11 22:42:23 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 gux 于 2021-7-11 22:42 编辑

以下程序生成了一个BeautifulSoup对象soup, 并打印 soup.prettify():

  1. from urllib.request import urlopen
  2. from urllib.error import HTTPError
  3. from bs4 import BeautifulSoup
  4. from urllib.parse import urljoin
  5. from urllib.request import pathname2url


  6. def path2url(path):
  7.     return urljoin('file:', pathname2url(path))

  8. html = urlopen(path2url('D:\\Webscraping\\Mathematics authors_titles \'new\'.html'), 'r')
  9. soup = BeautifulSoup(html, 'html.parser')
  10. print(soup.prettify())
复制代码


运行结果的前几行为

i
                      </span>
                      <span style="display: inline-block; width: 0px; height: 3.993em;">
                      </span>
                     </span>
                    </span>
                   </span>
                  </span>
                 </span>
                 <span style="display: inline-block; width: 0px; height: 3.993em;">
                 </span>



soup.prettify() 是一个字符串对象:

  1. print(type(soup.prettify()))
复制代码


的运行结果为

<class 'str'>

然而,当我试图把 soup.prettify() 写入一个txt文件时,发生了异常:

  1. from urllib.request import pathname2url


  2. def path2url(path):
  3.     return urljoin('file:', pathname2url(path))

  4. html = urlopen(path2url('D:\\Webscraping\\Mathematics authors_titles \'new\'.html'), 'r')
  5. soup = BeautifulSoup(html, 'html.parser')

  6. with open('arxiv_new.txt', 'w') as arxiv_new:
  7.     arxiv_new.write(soup.prettify())
复制代码


运行时出现异常

Traceback (most recent call last):
  File "D:\Webscraping\arxiv_math_new.py", line 18, in <module>
    arxiv_new.write(soup.prettify())
UnicodeEncodeError: 'gbk' codec can't encode character '\u22ca' in position 28183: illegal multibyte sequence

为什么一个字符串对象能被打印,却不能写入文件?



最佳答案
2021-7-11 22:57:03

网页获取的字符串编码和你 txt 文件的编码不同呗,编码不相同自然写入要么会报错、要么乱码

字符串是 utf-8 编码的可能,你 open 那加上 encoding = 'utf-8' 应该就可以了

参考代码:

  1. with open('arxiv_new.txt', 'w', encoding='utf-8') as arxiv_new:
  2.     arxiv_new.write(soup.prettify())
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-7-11 22:57:03 | 显示全部楼层    本楼为最佳答案   

网页获取的字符串编码和你 txt 文件的编码不同呗,编码不相同自然写入要么会报错、要么乱码

字符串是 utf-8 编码的可能,你 open 那加上 encoding = 'utf-8' 应该就可以了

参考代码:

  1. with open('arxiv_new.txt', 'w', encoding='utf-8') as arxiv_new:
  2.     arxiv_new.write(soup.prettify())
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-7-12 09:49:22 | 显示全部楼层
Twilight6 发表于 2021-7-11 22:57
网页获取的字符串编码和你 txt 文件的编码不同呗,编码不相同自然写入要么会报错、要么乱码

字符串是  ...

非常感谢!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-21 20:36

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表