gpt4 book ai didi

python - BeautifulSoup 解析

转载 作者:行者123 更新时间:2023-11-30 22:55:24 24 4
gpt4 key购买 nike

我一直在努力使用 BeautifulSoup 解析这棵树以获得我正在寻找的文本。美化 HTML 后,我最终得到了一个我感兴趣的表格。

    <td>
<a href="/inventoryCheck/16783169/?zip=93817">
<h3>
Product A
</h3>
</a>
<a class="show_hide" href="/inventoryCheck/16783169/?zip=93817" style="color:red">
Not Available
</a>
<br/>
Available at roughly
<a style="color:red">
0%
</a>
of Stores Nationwide
</td>
</tr>
<tr>
<td style="padding:10px">
<a href="/inventoryCheck/32201303/?zip=93817">
<img src="/prod_image/32201303.jpg"/>
</a>
</td>
<td>
<a href="/inventoryCheck/32201303/?zip=93817">
<h3>
Product B
</h3>
</a>
<a class="show_hide" href="/inventoryCheck/32201303/?zip=93817" style="color:red">
Not Available
</a>
<br/>
Available at roughly
<a style="color:red">
0%
</a>
of Stores Nationwide
</td>
</tr>
<tr>
<td style="padding:10px">
<a href="/inventoryCheck/29236000/?zip=93817">
<img src="/prod_image/29236000.jpg"/>
</a>
</td>
<td>
<a href="/inventoryCheck/29236000/?zip=93817">
<h3>
Product C
</h3>
</a>
<a class="show_hide" href="/inventoryCheck/29236000/?zip=93817" style="color:red">
Not Available
</a>
<br/>
Available at roughly
<a style="color:red">
0%
</a>
of Stores Nationwide
</td>
</tr>
<tr>
<td style="padding:10px">
<a href="/inventoryCheck/35536199/?zip=93817">
<img src="/prod_image/35536199.jpg"/>
</a>
</td>
<td>
<a href="/inventoryCheck/35536199/?zip=93817">
<h3>
Product D
</h3>
</a>
<a class="show_hide" href="/inventoryCheck/35536199/?zip=93817" style="color:red">
Not Available
</a>
<br/>
Available at roughly
<a style="color:red">
0%
</a>
of Stores Nationwide
</td>

“h3”标签表示产品,因此我想抓取该标签内的文本,如果有 h3,那么我还想查看下一个“a”标签,看看该产品是否可用。

最终在 Python 中,我只想要一行包含产品名称及其可用性的行。

我尝试过使用 .children、.descendants 等,但确实一事无成。

有人可以提供线索吗?

最佳答案

您要查找的是 .parent.nextSibling 属性。它们帮助您相对于 h3 标签导航树。关于 BeautifulSoup(以及任何 HTML/XML/等)要记住的重要一点是它是基于树的。 HTML 的大致结构如下:

td
├─ a
│  └─ h3
├─ a
├─ a
└─ br

因此,您的 h3 是第一个 a 的子级,也是您想要的 a 的“侄女/侄子”。因此,您需要获取 h3 的父级的下一个兄弟级。 BeautifulSoup 文档中有一个关于 navigating the tree 的很好的部分。 .

试试这个:

from bs4 import BeautifulSoup

testdata = """
Your data here
"""

soup = BeautifulSoup(testdata)

items = []

for item in soup.find_all('h3'):
name = item.text
availability = item.parent.nextSibling.text

items.append({'name': name, 'availability': availability})

您将获得一个 items 数组,其中包含每个产品的字典:

 [{'name': u'Product A', 'availability': u'Not Available'},
{'name': u'Product B', 'availability': u'Not Available'},
{'name': u'Product C', 'availability': u'Not Available'},
{'name': u'Product D', 'availability': u'Not Available'}]

关于python - BeautifulSoup 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37441692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com