python - 使用 BeautifulSoup 通过 id 获取 div 的内容

标签 python html python-2.7 beautifulsoup html-parsing

我正在使用 python2.7.6、urllib2 和 BeautifulSoup

从网站中提取 html 并存储在变量中。

如何使用 beautifulsoup 仅显示带有 id 的 div 的 html 内容?

<div id='theDiv'>
<p>div content</p>
<p>div stuff</p>
<p>div thing</p>

会是

<p>div content</p>
<p>div stuff</p>
<p>div thing</p>

最佳答案

加入div标签的元素.contents :

from bs4 import BeautifulSoup

data = """
<div id='theDiv'>
    <p>div content</p>
    <p>div stuff</p>
    <p>div thing</p>
</div>
"""

soup = BeautifulSoup(data)
div = soup.find('div', id='theDiv')
print ''.join(map(str, div.contents))

打印:

<p>div content</p>
<p>div stuff</p>
<p>div thing</p>

关于python - 使用 BeautifulSoup 通过 id 获取 div 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25614702/

相关文章:

javascript - 使用 javascript 构建 html 标签

javascript - 向 WordPress 添加自定义 JavaScript、CSS 和 HTML

Python线程调度

python - RESTful API - 在 html 表中显示返回的 json

python - 检查键是否在字典中并在同一个 "if"中获取它的值是否安全?

python - 将 Dash 应用程序集成到 Flask : minimal example

java - 嵌套的要点列表文本到 HTML

python - 如何将python脚本添加到Windows系统路径?

python - 如何使用 scrapy 和 python 动态抓取 Tripadvisor

python - 转换oracle日期格式