繁体   English   中英

如何使用 BeautifulSoup 从“a”元素中提取文本?

[英]How to extract text from 'a' element with BeautifulSoup?

我正在尝试从使用 beautifulsoup 获得的“a”html 元素中获取文本。 我可以打印整个东西,我想找到的东西就在那里:

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

但是当我想更具体并从中获取文本时,它会给我这个错误:

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

这是我正在运行的代码:

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)

我已经搜索了我的问题,但找不到有用的东西。

美丽的汤在搜索中没有找到值时返回 -1 这在 python 中不是很常见的方式来显示不存在值,但它是其他语言的常见方式。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM