Python Forum
Failure to open web pages
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Failure to open web pages
#1
The code is supposed to open 5 links e new tabs but it's given a error.
The code was written bellow:

#! python3
# lucky.py - Opens several Google search results.
import requests, sys, webbrowser, bs4
print('Googling...')  # display text while downloading the Google page
res = requests.get('http://google.com/search?q=python' + ' '.join(sys.argv))
res.raise_for_status()
print(sys.argv[1:])
# Retrieve top search result links.
soup = bs4.BeautifulSoup(res.text, features="html.parser")
# Open a browser tab for each result.
linkElems = soup.select('.r a')
# Open a browser tab for each result.
link_elems = soup.select('.r a')
numOpen = max(5, len(linkElems))
print(numOpen)
for i in range(numOpen):
    webbrowser.open('http://google.com/search?q=' + link_elems[i].get('href'))
This is the error
Error:
Traceback (most recent call last): File "C:/Users/-/PycharmProjects/guppe/testandohtml.py", line 17, in <module> webbrowser.open('http://google.com/search?q=' + link_elems[i].get('href')) IndexError: list index out of range
The exemple is from the book : 'Automate the Boring Stuff with Python', Thanks
Reply
#2
How many element are there in link_elems? You do know why you are getting this error right? It's because the index you trying to access doesn't exist in the list.

Like, (this is a hypothetical situation) your list has maybe 3 elements. And you're trying to access the fourth. So an an error occurs.

You need to figure out why this is happening.
Reply
#3
FYI: A few empty lines, here and there, will improve readability of code dramatically.
Reply
#4
may be you want to change the line 14 to
numOpen = min(5, len(linkElems))
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020