【Python】关于BeautifulSoup的小实例(1)
这是一个简单的HTML页面,请保存为字符串,完成后面的计算要求:
<html>
<head>
<title>simple test</title>
</head>
<body>
<p id='china'>中国,<b>你好!</b>.</p>
<p id='world'>世界,<b>大同!</b>.</p>
</body>
</html>
(1)打印head标签的内容
(2)获取body标签的内容
(3)获取id为china的标签对象
(4)获取并打印HTML页面中的中文字符
(1)
import requests
from bs4 import BeautifulSoup
r='<html><head><title>simple test</title></head><body><p id="china">中国,<b>你好!</b>.</p><p id="world">世界,<b>大同!</b>.</p></body></html>'
soup=BeautifulSoup(r)
print(soup.head)
(2)
>>>print(soup.body)
(3)
>>>print(soup.find(id='china'))
(4)
>>>for i in r:
if('\u4e00' <= i <= '\u9fff'): #检测单个字符是否为汉字
list_.append(i) #是则将单个字符加入列表
>>>print(''.join(list_)) #以空字符作为分割符转换为str形式