V
V
Vasily Sheshunov2022-01-29 18:46:16
Python
Vasily Sheshunov, 2022-01-29 18:46:16

Loop in parsing?

I'm learning parsing, I'm completely confused with one task.
I will be grateful for the answer. The question is how to write a loop that would collect information from block a.
Located in the code like this:
How do I write code so that it can find a ?

here is my code which finds nothing.

items = soup.find_all("div", class_="catalog-grid__item")
        for catalog in items:
            catalog_title = catalog.find('a', class_="product-snippet__desc")
            print(catalog_title)


-div "catalog-grid__item'
   -artical “product-snippet”
      -div “product-snippet__top”
         -div “product-snippet__right”
            -div “product-snippet__desc”
               -a
               -a
               -a
               -a
               -a
               -...
-div "catalog-grid__item'
   -artical “product-snippet”
      -div “product-snippet__top”
         -div “product-snippet__right”
            -div “product-snippet__desc”
               -a
               -a
               -a
               -a
               -a
               -...
-div "catalog-grid__item'
   -artical “product-snippet”
      -div “product-snippet__top”
         -div “product-snippet__right”
            -div “product-snippet__desc”
               -a
               -a
               -a
               -a
               -a
               -...
-...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dr. Bacon, 2022-01-29
@bacon

Well, 'product-snippet__desc' is on 'div', not 'a'. And why do you need to search for "catalog-grid__item" when you can immediately search for all 'a' inside 'product-snippet__desc'.

D
Denis Shavaleev, 2022-01-29
@Shavaleev_DieZ

In a previous reply, Dr. Bacon correctly pointed out your mistakes.
The result will be something like this:

"""Изначальный вариант, подразумевается что <a> только в структуре, что вы привели"""
items = soup.find_all("a")
for catalog in items:
    catalog_title = catalog.text
    print(catalog_title)
 
"""Если тег <a> еще где-то присутствет на странице"""
items = soup.find_all("div", class_="product-snippet__desc")
for catalog in items:
    a_tags = catalog.find_all("a")
    for a in a_tags:
        catalog_title = a.text
        print(catalog_title)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question