我试图用漂亮的soup解析python中的以下HTML代码。我希望能够搜索标签内的文本,例如“Color”并返回下一个标签“Slate,mykonos”的文本,然后对下一个标签这样做,这样对于一个给定的文本类别,我可以返回它的相应信息。在
但是,我发现很难找到合适的代码来实现这一点。在
<h2>Details</h2>
<div class="section-inner">
<div class="_UCu">
<h3 class="_mEu">General</h3>
<div class="_JDu">
<span class="_IDu">Color</span>
<span class="_KDu">Slate, mykonos</span>
</div>
</div>
<div class="_UCu">
<h3 class="_mEu">Carrying Case</h3>
<div class="_JDu">
<span class="_IDu">Type</span>
<span class="_KDu">Protective cover</span>
</div>
<div class="_JDu">
<span class="_IDu">Recommended Use</span>
<span class="_KDu">For cell phone</span>
</div>
<div class="_JDu">
<span class="_IDu">Protection</span>
<span class="_KDu">Impact protection</span>
</div>
<div class="_JDu">
<span class="_IDu">Cover Type</span>
<span class="_KDu">Back cover</span>
</div>
<div class="_JDu">
<span class="_IDu">Features</span>
<span class="_KDu">Camera lens cutout, hard shell, rubberized, port cut-outs, raised edges</span>
</div>
</div>
我使用以下代码检索我的div标记
^{pr2}$一旦我检索到标记,我就可以在其中导航,但我找不到正确的代码,使我能够找到一个标记内的文本,并在标记之后返回该标记中的文本。在
任何帮助都会非常感谢,因为我是python新手,而且我已经走到了死胡同。在
试试看。它还可以为您提供相应的值。请确保将
html elements
括在content=""" """
变量内,并用三个引号括起来,看看它是如何工作的。在您可以定义一个函数来返回您输入的键的值:
输出:
^{pr2}$我希望这就是你要找的。在
说明:
soup.find('span', text=key)
返回<span>
标记,其text=key
。在.parent
返回当前<span>
标记的父标记。在示例:
当
key='Color'
时,soup.find('span', text=key).parent
将返回现在我们把它存储在
key_tag
。只剩下第二个<span>
的文本,这是key_tag.find_all('span')[1].text
行所做的。在相关问题 更多 >
编程相关推荐