python - BeautifulSoup如何解析没有标签的元素
问题描述
我对解析有一点问题。我有身体=
<div class='contact'>
<i class='fa fa phone'></i>
Text what I want
</div>
我有很多类似的代码。我用 =
def get_html(url):
response = requests.get(url)
return response.text
def get_all_links(html):
soup = BeautifulSoup(html, "html.parser")
tds = soup.find('div', class_='col-xs-7 insInfoRow onlyGal')
link = []
for i in tds:
link.append(i)
return link
我只想要这个文本。请帮助
解决方案
为您提供的示例代码。.text
可以直接从元素中获取文本内容。
from bs4 import BeautifulSoup
html="""
<div class='contact'>
<i class='fa fa phone'></i>
Text what I want
</div>
<div class='contact'>
<i class='fa fa phone'></i>
Text what I want too
</div>
"""
soup = BeautifulSoup(html, "html.parser")
divs = soup.find_all('div', class_='contact')
print([div.text.strip() for div in divs])
PS:.strip()
可以去掉空格。
推荐阅读
- apache - macos mamp 上的虚拟主机 ERR_CONNECTION_REFUSED
- tensorflow - 当我更改输出层的激活函数时,模型不会学习
- javascript - 孩子到父母到另一个孩子之间的Vue通信
- android - 如何将函数中的字符串类型参数传递给 Flutter 中的 IconData
- powerbi - 导入excel文件时Power Bi日期错误
- javascript - 如何从嵌入在 MongoDB 对象数组中的数组中提取值?
- angular - Angular / Rxjs如何订阅具有不同参数的循环中的函数
- c++ - 释放 3 维向量 C++
- javascript - 将字符串值转换为 int (esp32)
- mysql - 使用一个接一个的值进行查询,为一堆值工作