获取标签内容(使用string,提取em中的内容)
由于 find_all() 返回的是一个列表,我们不能直接调用 .string 属性。
我们需要使用 for 循环遍历列表,获取每一个节点字符串,再来调用 .string 属性获取节点中的标签里的内容。
# 使用import导入requests模块
import requests
# 从bs4中导入BeautifulSoup模块
from bs4 import BeautifulSoup
# 将URL地址赋值给变量url
url = "https://nocturne-spider.baicizhan.com/2020/08/07/1/"
# 将变量url传入requests.get(),赋值给response
response = requests.get(url)
# 将服务器响应内容转换为字符串形式,赋值给html
html = response.text
# 使用BeautifulSoup()读取html,添加lxml解析器,赋值给soup
soup = BeautifulSoup(html, "lxml")
# 使用find_all()查询soup中em的节点,赋值给content_all
content_all = soup.find_all(name="em")
# for循环遍历content_all
for content in content_all:
# 获取每个节点中标签内的内容,赋值给contentString
contentString = content.string
# 使用print输出contentString
print(contentString)
PS:windows系统使用Ctrl+F
代码总结:
Import requests
From bs4 import BeautifulSoup
url=“http://+地址+/”
response=request.get(url)//找到网页
html=response.text//转化字符串
soup=BeautifulSoup(http,“lxml”)//将HTML标准化
content_all=soup.find_all(name=”p”)
for content in content_all:
contentSoup=content.string//提取文字内容
print(contentSoup)
关于string的一些小知识
提取节点包含多个子节点时:
当定位的节点中同时包含了多个子节点时,示例中标黄的部分:有两个节点,一个节点是 em 标签内容,另一个节点是纯文字。
使用 .string 属性 属性时,不清楚应该调用哪个节点的内容,会返回None值。
关于text的一些小知识
遇到节点中既包含其他节点,也有文字时,可以使用 .text 属性来提取内容。
.text 属性能直接提取该节点中的所有文字,并返回字符串格式。
使用 .text 属性来提取 p 节点中的所有的文字内容并输出。注意:这里的 .text 属性,用法是获取节点中的所有文字内容。
获取响应内容的 response.text 属性中的 .text 用于提取响应消息中的内容。
两段代码示例:
1.0
# 定义html
html = """
<p>
<em>夜曲编程</em>
这是一个段落
</p>"
# 从bs4中导入BeautifulSoup模块
from bs4 import BeautifulSoup
# 使用BeautifulSoup()读取html,添加lxml解析器,赋值给soup
soup = BeautifulSoup(html, "lxml")
# 使用find_all()查询soup中p节点,赋值给content_all
content_all = soup.find_all(name="p")
# for循环遍历content_all
for content in content_all:
# 获取节点内的全部内容,赋值给contentString
contentString = content.text
# 使用print输出contentString
print(contentString)
2.0
# 使用import导入requests模块
import requests
# 从bs4中导入BeautifulSoup模块
from bs4 import BeautifulSoup
# 将URL地址赋值给变量url
url = "https://nocturne-spider.baicizhan.com/2020/08/08/%E5%9F%9F%E5%90%8D/"
# 将变量url传入requests.get(),赋值给response
response = requests.get(url)
# 将服务器响应内容转换为字符串形式,赋值给html
html = response.text
# 使用BeautifulSoup()读取html,添加lxml解析器,赋值给soup
soup = BeautifulSoup(html, "lxml")
# 使用find_all()查询soup中h2节点,赋值给content_all
content_all = soup.find_all(name="h2")
# for循环遍历content_all
for content in content_all:
# 使用.string获取节点的内容,赋值给contentString
contentString = content.string
# 使用print输出contentString
print(contentString)
# 使用.text获取节点的内容,赋值给contentString
contentString = content.text
# 使用print输出contentString
print(contentString)
使用 find_all() 函数查找 <h2> 节点。for循环遍历列表,分别用 .string 属性和 .text 属性提取节点中的内容并输出。
使用.string 属性提取的内容为None。
第五天在夜曲的打卡