Galactic GreenLemon
Galactic GreenLemon

Reputation: 15

How to extract text from 'a' element with BeautifulSoup?

I'm trying to get the text from a 'a' html element I got with beautifulsoup. I am able to print the whole thing and what I want to find is right there:

-1
<a href="/manga/tensei-shitara-slime-datta-ken-fuse">Tensei Shitara Slime Datta Ken Manga</a>
-1

But when I want to be more specific and get the text from that it gives me this error:

  File "C:\python\manga\manga.py", line 15, in <module>
    print(title.text)
AttributeError: 'int' object has no attribute 'text'

Here is the code I'm running:

import requests
from bs4 import BeautifulSoup

URL = 'https://mangapark.net/manga/tensei-shitara-slime-datta-ken-fuse'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')

results = soup.find('section', class_='manga')

manga_title = soup.find('div', class_='pb-1 mb-2 line-b-f hd')


for m_title in manga_title:
    title = m_title.find('a')
    print(title.text)

I've searched for my problem but I couldn't find something that helps.

Upvotes: 0

Views: 109

Answers (1)

Aasim Sani
Aasim Sani

Reputation: 339

Beautiful soup returns -1 as a value when it doesn't find something in a search This isn't a very common way in python to show that no values exist but it is a common one for other languages.

import requests
from bs4 import BeautifulSoup

URL = 'https://mangapark.net/manga/tensei-shitara-slime-datta-ken-fuse'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')

results = soup.find('section', class_='manga')

manga_title = soup.find('div', class_='pb-1 mb-2 line-b-f hd')

for m_title in manga_title.children:
    title = m_title.find('a')

    # Beautiful soup returns -1 as a value when it doesn't find something in a search
    # This isn't a very pythonic way to show non existent values but it is a common one
    if title != -1: 
        print(title.text)

Output

Tensei Shitara Slime Datta Ken Manga

Upvotes: 2

Related Questions