pratheeraja pratheeraja - 2 months ago 16
Python Question

result printing twice while using beautifulsoup module in python

I just started to use beautifulsoup module in Python, and my code is to see the live cricket score from a website. I did it somehow, but the result is printing twice.

here is my code

import requests, bs4
from BeautifulSoup import *

res = requests.get('http://www.cricbuzz.com/cricket-match/live-scores')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text)
mydivs = soup.findAll("div", { "class" : "cb-lv-scrs-col cb-font-12 text-black" })
le=len(mydivs)
result=""
for l in range(0,le-1):
result += str(mydivs[l].text)+'\n'
print(result)


and the result is like:

IND129/2 (26.5 Ovs) • ZIM126 (34.3 Ovs)

WI266/6 (45.4 Ovs) • AUS265/7 (50.0 Ovs)

IND129/2 (26.5 Ovs) • ZIM126 (34.3 Ovs)

WI266/6 (45.4 Ovs) • AUS265/7 (50.0 Ovs)

please let me know where i have made mistakes

Answer

I've edited your code with proper indendation and hope that works for you.

For the above code,

import requests, bs4

res = requests.get('http://www.cricbuzz.com/cricket-match/live-scores')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text)
mydivs = soup.findAll("div", { "class" : "cb-lv-scrs-col cb-font-12 text-black" })
le = len(mydivs)
result = ""
for l in range(0,le-1):
    result += mydivs[l].text + "\n"
print(result)

The output I've got is,

IND 129/2 (26.5 Ovs)  •  ZIM 126 (34.3 Ovs)
WI 266/6 (45.4 Ovs)  •  AUS 265/7 (50.0 Ovs)

So, I believe that you've put the print inside the for loop.