2
try:
    src = soup.find("div", {"id": "image-block"})
except AttributeError:
    continue

It works great, but the problem is:
when I get one url it's ok, but when I receive five urls they come inside the same variable.

I need to specify 10 variables:

  • img1
  • img2
  • img3
  • ...

If BS finds only 1 url it puts it into url 1, but if BS finds 3 urls, it separates them and puts them into different variables.

Thanks you for your help

EDIT

Thanks you so much for your help but sometime i have 1 image to get and sometime 8.

So i get this :

var1, var2, var3, var4, var5,var6, var7, var8 = soup.find_all("div", {"id": "image-block"})

ValueError: not enough values to unpack (expected 8, got 1)

But if i put : var1 = soup.find_all("div", {"id": "image-block"}) it's works but put all in var1

My problem is that i don't know how much image i have to get on each loop.

Thank you again for you time.

1 Answers1

1

I need to specify 10 variables img1 img2 img3:

You can use find_all(). Since find_all() returns a ResultSet (a list), you can unpack the variables as follows:

from bs4 import BeautifulSoup

html_doc = """\
<img src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.com" width="104" height="142">
<img src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.com" width="104" height="142">
<img src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.com" width="104" height="142">
<img src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.com" width="104" height="142">
<img src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.com" width="104" height="142">
"""
soup = BeautifulSoup(html_doc, "html.parser")

var1, var2, var3, var4, var5 = soup.find_all('img')

this will create 5 different variables: var1, var2, etc.

Make sure the length of the variables you are unpacking is the same length that .find_all() returns.

See also

How to assign each element of a list to a separate variable?

MendelG
  • 14,885
  • 4
  • 25
  • 52
  • What do you think about this way longueur = len(total) if (longueur)==1: var1= soup.find_all("div", {"id": "image-block"}) print(longueur) if (longueur)==2: var1,var2= soup.find_all("div", {"id": "image-block"}) print(longueur) – steve figueras Jan 05 '23 at 21:49