Python Forum

Full Version: Who can help the SyntaxError: expected ':' for forloop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)

what wrong of this python program?
The python show below error:
File "C:\Users\user\Documents\Beautifulsoup sample.py", line 19
for i in range(1,len(list1))
^
SyntaxError: expected ':'
Use code tags.
Need for i in range(1,len(list1)):
Also do not loop like this,just loop over the tags.
Example:
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)

# Just some examples with CCS seletor
# 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)'))
Output:
Hellow World1 Hellow World2 Hellow World3 ------------------------- ['Hellow World1', 'Hellow World2', 'Hellow World3'] <p>Hellow World2</p>