[英]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.