Home>

gives all links of the site, how to make the first one?

link= Soup.findall ('Div', attrs= {'class': 'item-title text-short'})
For Div in Link:
    Print (Div.find ('A') ['href'])

Error

Print (Div.find ('A') ['href'])
TypeRorror: 'Nonetype' Object Is Not Subscriptable
  • Answer # 1

    method Div.Find ('A') returned None because tag A. not found, respectively, None ['href'] And caused an error in the question.

    I can suggest checking:

    for Div in Link:
        a= div.find ('a')
        If a:
            Print (A ['href'])
    

    or alternative check:

    for Div in Link:
        a= div.find ('a')
        IF Not A:
            Continue.
        Print (A ['href'])
    

    And how to do to give out only the first link?

    qwe2021-04-09 08:37:39

    There are different ways, for example, after print (a ['href']) write a break and cycle will finish early

    gil9red2021-04-09 08:37:39

    Many thanks!

    qwe2021-04-09 08:37:39

    Then, mark the answer as correct so as not to hang a question without an answer

    gil9red2021-04-09 08:37:39
  • Answer # 2

    For a complex search, I would better CSS selectors used

    Soup.Select ('Div.Item-Title.Text-Short A')
    

    This request will return a list of all elements A, which are inside the DIV tag with classes of Item-Title and Text-Short. Next, just take the first element -this will be the first link.

    And even better not to search for the desired item by number, but to set the exact condition by class or ID. It does not complicate CSS Selecom, but such a request will be more resistant to page changes.