gpt4 book ai didi

python - 使用 .find() 从 BS4 的 html 页面中提取 2 个相同的 'div' 中的第二个

转载 作者:行者123 更新时间:2023-12-01 00:46:50 28 4
gpt4 key购买 nike

我正在尝试从 soup 元素中提取 2 个相同“div”中的第二个。当解析槽并使用 .find() 方法提取时,它只获取顶部的第一个。如果满足某些条件,如何告诉脚本跳过第一个并获取下一个?下面是我要从中提取的 html 代码。

<div class="a-row a-size-base a-color-secondary"><span>MPAA Rating: PG (Parental Guidance Suggested)</span></div>
</div>
</div></div>
<div class="sg-1"><div class="sg-2">
<div class="a-section a-spacing-none a-spacing-top-small">
<div class="a-row a-size-base a-color-base">
</div>
</div>
<div class="a-section a-spacing-none a-spacing-top-mini">
<div class="a-row a-size-base a-color-secondary"><span>$0.00 with a CONtv trial on Prime Video Channels</span></div>
</div>

这是我正在尝试的代码:

if '$' not in str(product.find('div', {'class': 'a-row a-size-base a-color-secondary'})):
print('NOT IN')
pass
price = product.find('div', {'class': 'a-row a-size-base a-color-secondary'})
print(price)
else:
price = product.find('div', {'class': 'a-row a-size-base a-color-secondary'})
print(price)

但是结果它仍然给了我这个:

NOT IN
<div class="a-row a-size-base a-color-secondary"><span>MPAA Rating: PG (Parental Guidance Suggested)</span></div>

而不是这样:

<div class="a-row a-size-base a-color-secondary"><span>$0.00 with a CONtv trial on Prime Video Channels</span></div> 

有什么建议吗?

最佳答案

您需要 find_all 然后索引到返回的列表,因为 find 只返回第一个匹配项。您可以使用 select 执行相同的操作。与 bs4 4.7.1。您可以使用 :contains 通过子字符串定位元素的 innerText (例如 CONtv Trial),然后使用 select_one如果需要第一个匹配,或者如果有多个匹配,则选择选择。在尝试访问 .text

之前,您需要先测试 if None
from bs4 import BeautifulSoup as bs
import requests

html = '''
<div class="a-row a-size-base a-color-secondary"><span>MPAA Rating: PG (Parental Guidance Suggested)</span></div>
</div>
</div></div>
<div class="sg-1"><div class="sg-2">
<div class="a-section a-spacing-none a-spacing-top-small">
<div class="a-row a-size-base a-color-base">
</div>
</div>
<div class="a-section a-spacing-none a-spacing-top-mini">
<div class="a-row a-size-base a-color-secondary"><span>$0.00 with a CONtv trial on Prime Video Channels</span></div>
</div>
'''
soup = bs(html, 'lxml')
print(soup.find_all('div', {'class': 'a-row a-size-base a-color-secondary'})[1].text)
print(soup.select('.a-color-secondary')[1].text)
print(soup.select_one('.a-color-secondary:contains("CONtv trial")').text)
<小时/>

使用 find_all 循环

matches = soup.find_all('div', {'class': 'a-row a-size-base a-color-secondary'})
for item in matches:
if '$' in str(item):
print(item.text)

关于python - 使用 .find() 从 BS4 的 html 页面中提取 2 个相同的 'div' 中的第二个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56919330/

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