bs4库的prettify()方法

xiaoxiao2021-02-28  68

基于bs4库HTML的格式输出

如何让<html>页面更友好的显示

prettify()方法:

>>> import requests >>> r = requests.get("http://python123.io/ws/demo.html") >>> demo = r.text >>> demo '<html><head><title>This is a python demo page</title></head>\r\n<body>\r\n<p class="title"><b>The demo python introduces several python courses.</b></p>\r\n<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>\r\n</body></html>' >>> from bs4 import BeautifulSoup >>> soup = BeautifulSoup(demo,"html.parser") >>> soup.prettify() '<html>\n <head>\n <title>\n This is a python demo page\n </title>\n </head>\n <body>\n <p class="title">\n <b>\n The demo python introduces several python courses.\n </b>\n </p>\n <p class="course">\n Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\n <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">\n Basic Python\n </a>\n and\n <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">\n Advanced Python\n </a>\n .\n </p>\n </body>\n</html>' >>> print(soup.prettify()) <html> <head> <title> This is a python demo page </title> </head> <body> <p class="title"> <b> The demo python introduces several python courses. </b> </p> <p class="course"> Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses: <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1"> Basic Python </a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2"> Advanced Python </a> . </p> </body> </html> >>> >>> print(soup.a.prettify()) #取出soup中的a标签进行prettify()方法处理 <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1"> Basic Python </a>

prettify()方法在实际调用bs4库时可以起到很好的辅助作用

注意 :bs4库中的编码问题:

bs4库将任何读入的html文件或字符串都转换为utf-8编码

python3.系默认支持字符编码utf-8

>>> soup = BeautifulSoup("<p>中文</p>","html.parser") >>> soup.p.string '中文' >>> print(soup.p.prettify()) <p> 中文 </p>

转载请注明原文地址: https://www.6miu.com/read-2628437.html

最新回复(0)