将文本输出与BeautifulSoup组合

2024-10-01 04:55:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我在解析文件中的链接时遇到问题,因为它不是完整链接,要解析的文本是:

<enclosure url="/itunes/463/RKBU-How-the-Seas-Shaped-Humanit-02019_09_24_13_40_18-0.mp3" length="83586948" type="audio/mpeg"/>

链接应为:

https://www.opednews.com/itunes/463/RKBU-How-the-Seas-Shaped-Humanit-02019_09_24_13_40_18-0.mp3

如何将网站地址的第一部分包含到以下输出中生成的链接中,以使地址完整?如有任何建议,将不胜感激

def get_playable_podcast1(soup1):
    subjects = []
    for content in soup1.find_all('item', limit=9):
        try:
            link = content.find('enclosure')
            link = link.get('url')
            print("\n\nLink: ", link)
            title = content.find('title')
            title = title.get_text()
        except AttributeError:
            continue
        item = {
                'url': link,
                'title': title,
                'thumbnail': "https://upload.wikimedia.org/wikipedia/en/thumb/2/21/OpEdNews_%28logo%29.jpg/200px-OpEdNews_%28logo%29.jpg",
        }
        subjects.append(item)
    return subjects

Tags: theurlgettitle链接linkcontentfind
1条回答
网友
1楼 · 发布于 2024-10-01 04:55:46

您可以将BeautifulSoupurllib.parse.urljoin一起使用:

import urllib.parse
from bs4 import BeautifulSoup as soup
url, html = 'https://www.opednews.com', '<enclosure url="/itunes/463/RKBU-How-the-Seas-Shaped-Humanit-02019_09_24_13_40_18-0.mp3" length="83586948" type="audio/mpeg"/>'
result = urllib.parse.urljoin(url, soup(html, 'html.parser').enclosure['url'])

输出:

'https://www.opednews.com/itunes/463/RKBU-How-the-Seas-Shaped-Humanit-02019_09_24_13_40_18-0.mp3'

相关问题 更多 >