在这里插入代码片
#coding=utf-8
import requests
from bs4 import BeautifulSoup
url='https://baike.baidu.com/item/Python/407313?fr=aladdin'
response=requests.get(url,headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36'
})
response.encoding='utf-8'
html=response.text
soup=BeautifulSoup(html,'lxml')
# .string可以返回当前节点中的内容,但是当前节点包含子节点时,.string不知道要获取哪一个节点中的内容,故返回空
#
# .text(或者.get_text())可以返回当前节点所包含的所有文本内容,包括当前节点的子孙节点
print(soup.title.string)
print(soup.title.text)
print(soup.head.string)
print(soup.head.text)
首先这段网页源代码的部分是这样的:
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta name="referrer" content="always" />
<meta name="description" content="Python是一种跨平台的计算机程序设计语言。是一种面向对象的动态类型语言,最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越来越多被用于独立的、大型项目的开发。...">
<title>Python(计算机程序设计语言)_百度百科</title>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<link rel="icon" sizes="any" mask href="//www.baidu.com/img/baidu.svg">
<meta name="keywords" content="Python PythonPython简介及应用领域 Python下载Python Python发展历程 Python风格 Python与MATLAB的对比 Python设计定位 Python执行 Python基本语法 Python帮助 PythonCGI Python特点 Python应用 Python工具功能 Python标准库 Python开发环境 Python解释器 Python著名应用 Python库导入 Python学习网站">
<meta name="image" content="https://bkssl.bdimg.com/cms/static/baike.png">
<script type="text/javascript">
// 配置 PD 监控。
window.alogObjectConfig = {
product: '103',
page: '103_1',
speed: {
sample: '0.008'
},
monkey: {
sample: '1',
hid: '1533'
},
exception: {
sample: '0.004'
},
feature: {
sample: '0.004'
},
csp: {
sample: '0.008',
'default-src': [
{match: '*.baidu.com,*.bdimg.com,localhost', target: 'Accept'},
{match: '*', target: 'Accept,Warn'}
]
}
};
当我使用python的BeautifulSoup对象,用string和text获取标签中的文字内容,效果是不一样的:
总结: