如何使用<br>美丽汤在标签之间抓取文本?



我正在尝试从<>标签,我感兴趣的文本字符串由
标签。

<div id="foo">
<p>
" Data 1 : Lorem"
<br>
<br>
" Data 2 : Ipsum"
<br>
</p>
<div>

期望输出:

Lorem

使用bs4,我被困在:

collection1 = soup.select('div#foo > p:-soup-contains("Data 1 : ")').replace("Data 1 : ","").text.strip()

我不知道如何为双引号或<br>标签设置分隔符?关于如何继续获得所需输出的任何想法吗?

我正试图删除这一页的详细信息。我试过了:

try:
collection = soup.select('div#ui-accordion-1-panel-1 > div.tab-content-wrapper > p:-soup-contains("Collection")').text.strip()
except:
collection = "" 
print("No Collection")              

期望得到整个<p>标签,但发生了异常。我一直在使用Selenium的其他片段,它确实工作。

下面是获取该数据的一种方法:

from bs4 import BeautifulSoup as bs
html = '''
<div id="foo">
<p>
" Data 1 : Lorem"
<br>
<br>
" Data 2 : Ipsum"
<br>
</p>
<div>
'''
soup = bs(html, 'html.parser')
desired_data = soup.select_one('div[id="foo"] p').contents[0].split(':')[1].replace('"', '').strip()
print(desired_data)

结果:

Lorem

这里有一种方法(在许多其他方法中)从该页获取集合信息:

from bs4 import BeautifulSoup as bs
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'
}
r = requests.get('https://www.messika.com/fr/bracelet-pm-diamant-or-rose-d-vibes-12350-pg', headers=headers)
soup = bs(r.text, 'html.parser')
info = [x for x in soup.select_one('div[class="tab-content product-details"] p:-soup-contains("Univers")').contents if 'Collection :' in x][0].split(':')[-1].strip()
print('Collection:', info)

结果:

Collection: D-Vibes

相关文档:https://beautiful-soup-4.readthedocs.io/en/latest/

在字符串中没有真正的",是的,您可以使用replace(),strip(),…或者使用dict,它还提供所有其他功能,并允许您从以下选项中进行选择:

data = dict(f.split(' : ') for f in soup.select_one('.tab-content-wrapper > p').stripped_strings if ':' in f)

将导致像这样的dict:

{'Référence': 'Bracelet D-Vibes petit modèle 12350-PG', 'Univers': 'Joaillerie', 'Collection': 'D-Vibes', 'Type de bijou': 'Bracelet diamant', 'Métal': 'Or rose', 'Pierres': 'Diamant', 'Poids total diamants': '0,45 carat, qualité G/VS', 'Longueur chaîne': '18 cm (5 anneaux de fermeture)', 'Catégorie': 'Bracelet femme'}

所以你可以简单地选择你的valuebykey:

data.get('Collection') if data.get('Collection') else 'No Collection'

这将给你:

D-Vibes

或者如果没有Collection

No Collection

from bs4 import BeautifulSoup
import requests
soup = BeautifulSoup(requests.get('https://www.messika.com/fr/bracelet-pm-diamant-or-rose-d-vibes-12350-pg').text)
data = dict(f.split(' : ') for f in soup.select_one('.tab-content-wrapper > p').stripped_strings if ':' in f)
data.get('Collection') if data.get('Collection') else 'No Collection'

最新更新