Использование BeautifulSoup для анализа данных в тегах / результатах - PullRequest
0 голосов
/ 13 июля 2020

Итак, у меня есть приведенный ниже код для анализа ссылки и заголовка, который отлично работает, но я хотел бы проанализировать только один сезон. Как видно из приведенной ниже ссылки / образца, данные о сезоне содержатся в тегах, поэтому поиск по тегу, очевидно, не будет работать. Как отфильтровать каждый сезон за раз? Любая помощь будет принята с благодарностью.

def get_playable_podcast0(soup0):
    subjects = []
    for content in soup0.find_all('item'):
        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': "(imagelink)",
        }
        subjects.append(item)
    return subjects
def compile_playable_podcast0(playable_podcast0):
    items = []
    for podcast in playable_podcast0:
        items.append({
            'label': podcast['title'],
            'thumbnail': podcast['thumbnail'],
            'path': podcast['url'],
            'is_playable': True,
    })
    return items

Образец из ссылки для анализа: . XML link

<item>
    <title>S7 E5</title>
    <enclosure url="https://cbc.mc.tritondigital.com/CBC_UNCOVER_P/media/uncover-Wm2KHbCU-20200707.mp3?ttag=season:7" length="41747493" type="audio/mpeg"/>
    <itunes:season>7</itunes:season>
    <itunes:episode>5</itunes:episode>
    <itunes:episodeType>full</itunes:episodeType>
</item>

Ответы [ 3 ]

0 голосов
/ 13 июля 2020

Вы можете выбрать season и преобразовать его в int. Но будьте осторожны, у некоторых предметов нет сезона: я устанавливаю сезон по умолчанию 1, если сезон отсутствует:

import requests
from bs4 import BeautifulSoup


url='https://www.cbc.ca/podcasting/includes/uncover.xml'
soup = BeautifulSoup(requests.get(url).content, 'xml')

for item in soup.select('item'):
    season = item.select_one('season')
    if season:
        season = int(season.text)
    else:
        season = 1  # default season is 1

    if season == 7:
        title = item.select_one('subtitle').text
        link = item.select_one('enclosure')['url']
        print(title)
        print(link)
        print('-' * 80)

Печать:

Glen faces new horrors while being locked up in prison. But then he makes a connection with someone on the outside who provides a lifeline — and possibly, a route to freedom.
https://cbc.mc.tritondigital.com/CBC_UNCOVER_P/media/uncover-Wm2KHbCU-20200707.mp3?ttag=season:7
--------------------------------------------------------------------------------
The day after Glen is convicted of murder he starts to work on his appeal. A new lawyer and an ex-RCMP private investigator find fresh evidence that should help get Glen a new trial.
https://cbc.mc.tritondigital.com/CBC_UNCOVER_P/media/uncover-SEmcfxRf-20200630.mp3?ttag=season:7
--------------------------------------------------------------------------------
The trial of Glen Assoun for the second degree murder of Brenda Way starts on June 1, 1999. But within days, the trial takes an expected turn, and events begin to unfold that place Glen in an impossible situation.
https://cbc.mc.tritondigital.com/CBC_UNCOVER_P/media/uncover-ba86fI2w-20200623.mp3?ttag=season:7
--------------------------------------------------------------------------------
The police investigation into Brenda Way’s murder is going nowhere until a new investigator is assigned to the case. Suddenly, new witnesses and evidence start to appear,  and all of it points in one direction.
https://cbc.mc.tritondigital.com/CBC_UNCOVER_P/media/uncover-EFf9iIoa-20200616.mp3?ttag=season:7
--------------------------------------------------------------------------------
On November 12, 1995, 28-year-old Brenda Way is found murdered behind an apartment building in Dartmouth, Nova Scotia.  Investigative journalist Tim Bousquet  discovers, right in his own neighbourhood,  a community of sex workers and a pattern of violence that indicates this is not the first time.
https://cbc.mc.tritondigital.com/CBC_UNCOVER_P/media/uncover-KuI2HiIz-20200616.mp3?ttag=season:7
--------------------------------------------------------------------------------
Twenty-five years ago, Brenda Way was found murdered in Dartmouth, Nova Scotia. A botched investigation followed, resulting in the wrongful imprisonment of Glen Assoun—who served more than 17 years for the crime. How could one investigation go so wrong? And where is the justice for Brenda?
https://cbc.mc.tritondigital.com/CBC_UNCOVER_P/media/uncover-EfLwkf1p-20200611.mp3?ttag=season:7
--------------------------------------------------------------------------------
0 голосов
/ 13 июля 2020

Это альтернативное решение, основанное на извлечении сезона из URL-адреса эпизода с помощью регулярного выражения, поскольку кажется, что URL-адреса всегда заканчиваются на '? Ttag = season: '. Насколько я могу судить, это, кажется, самый надежный источник информации, когда дело доходит до нумерации сезонов.

from bs4 import BeautifulSoup
import requests
import re

resp = requests.get('https://www.cbc.ca/podcasting/includes/uncover.xml')
soup = BeautifulSoup(resp.text)
epi_ls = get_playable_podcast0(soup) # using your function here
seasons = {}
for ep in epi_ls:
    ep_url = ep.get('url')
    regex_match = re.search("(?<=season:)[0-9]+", ep_url)
    if not regex_match:
        continue
    season_number = regex_match[0]
    if season_number in seasons:
        seasons[season_number].append(ep)
    else:
        seasons[season_number] = [ep]

Есть несколько эпизодов, которые не относятся к определенному сезону, например особенный сезон 1/3/5 (я видел что-то подобное), так что я думаю, что это не сработает для них. Преимущество этого метода заключается в том, что на него не влияет то, как авторы подкаста зарегистрировали неправильные itunes: season / itunes: episode для нескольких эпизодов. Примером этого является «S3 E3: Meet Me Under The Clock», который зарегистрирован с <itunes:season>1</itunes:season> и <itunes:episode>8</itunes:episode>.

0 голосов
/ 13 июля 2020

Попробуйте это, если я правильно понял ваш вопрос:

def get_playable_podcast0(soup0):
    subjects = []
    for content in soup0.find_all('item'):
          desiredSeason = "7"
          if content.find('itunes:season').text != desiredSeason:
             continue
          # rest of code as before
   
         
...