Forum Python

Please or S’enregistrer to create posts and topics.

Erreur de syntaxe sur BeautifulSoup

from bs4 import BeautifulSoup
html="""
<html>
<head>
<meta charset="utf-8"/8>
<title>Hello</title>
</head>
<body>
<p>Hellow World1</p>
<p>Hellow World2</p>
<p>Hellow World3</p>
</body>
</html>
"""
sp=BeautifulSoup(html,"html.parser")
list1=sp.find_all("p")
print(list1)
print(len(list1))
for i in range(1,len(list1))
print(list1[i])
#for i in range(len(list1))
# print(list1[i].text)

 

Qu'est-ce qui ne va pas dans ce programme Python ? Le Python affiche l'erreur suivante :

File "C:UsersuserDocumentsBeautifulsoup sample.py", line 19

for i in range(1,len(list1))

^ SyntaxError: expected ':'

Utilisez des balises de code.
Il faut écrire for i in range(1,len(list1)):
De plus, ne bouclez pas comme ceci, bouclez simplement sur les balises.
Exemple :

from bs4 import BeautifulSoup
html="""
<html>
<head>
<meta charset="utf-8"/8>
<title>Hello</title>
</head>
<body>
<p>Hellow World1</p>
<p>Hellow World2</p>
<p>Hellow World3</p>
</body>
</html>
"""
sp = BeautifulSoup(html, "html.parser")
list_p = sp.find_all("p")
for tag in list_p:
print(tag.text)

# Juste quelques exemples avec un sélecteur CSS
# https://www.w3schools.com/cssref/css_selectors.php
print('-' * 25)
print([tag.text for tag in sp.select('p')])
print(sp.select_one('p:nth-child(2)'))

 

Sortie :

Hellow World1
Hellow World2
Hellow World3

['Hellow World1', 'Hellow World2', 'Hellow World3']
<p>Hellow World2</p>