Python 使用 BeautifulSoup 按 id 获取 div 的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25614702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:23:37  来源:igfitidea点击:

Get contents of div by id with BeautifulSoup

pythonhtmlpython-2.7beautifulsouphtml-parsing

提问by user8028

I am using python2.7.6, urllib2, and BeautifulSoup

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

to extract html from a website and store in a variable.

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

How can I show just the html contents of a divwith an id by using beautifulsoup?

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

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

would be

将是

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

回答by alecxe

Join the elements of div tag's .contents:

加入 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))

Prints:

印刷:

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