Не удается найти контейнеры с BeautifulSoup - PullRequest
0 голосов
/ 15 января 2019

Я пытаюсь сделать очень простой скрипт, который будет очищать 50 лучших звуков SoundCloud, добавлять их в словарь, а затем сохранять их в файл. Когда я пытаюсь найти все элементы, я ничего не получаю (как видно из сообщения отладки, которое я вставил). Мне было интересно, что я сделал не так, и если кто-нибудь может помочь мне разобраться, спасибо!

from bs4 import BeautifulSoup as Bs
import requests

website = "https://soundcloud.com/charts/top?genre=rock&country=all-countries"
session = requests.session()


def get_songs():
    songs = {}
    response = session.get(website)
    soup = Bs(response.text, "html.parser")

print(soup.title.text)

containers = soup.find_all("li", {"class": "chartTracks__item"})

if len(containers) == 0:
    print("Could not find any containers")

for element in containers:
    chart_track_div = element.div("chartTrack")
    details_div = chart_track_div.div("chartTrack__details")
    artist = details_div.div("chartTrack__username").text
    song_name = details_div.div("chartTrack__title").text

    songs[song_name] = artist

return songs


def create_file(songs_dictionary):
# Just printing out key&value for now

    for key, value in songs_dictionary:
        print("Song: " + key)
        print("Artist: " + value)


toSave = get_songs()
create_file(toSave)

Вот что я получу после запуска: http://prntscr.com/m78dfr

1 Ответ

0 голосов
/ 15 января 2019

Несколько вещей, которые мне нужно было изменить.

Во-первых, это динамическая страница, поэтому, если вы хотите захватить эту информацию в контейнеры с помощью soup.find_all("li", {"class": "chartTracks__item"}), вам сначала нужно отобразить страницу, либо с помощью Selenium или html-запросы , затем выполните .find_all

Однако данные, которые вы извлекаете, находятся в источнике html, но под разными тегами, поэтому я просто выбрал информацию, которую вы собирали.

Во-вторых, я не знал, было ли это именно вашим намерением, но вы сохранили исполнителя в качестве имени пользователя и песню в качестве заголовка. К сожалению, каждая из этих песен имеет несколько разные форматы, перечисленные в Soundcloud. Если вы действительно хотите точно захватить название исполнителя, это потребует некоторой фильтрации и повторной работы со строками. Но я сохранил это, как и ты, и ты можешь выбирать, что делать дальше.

В-третьих, вы не передали никаких параметров в первую функцию:

def get_songs():
    songs = {}
    response = session.get(website)

Так что он ничего не собирается делать, поскольку он ссылается на website, но никогда не передается. Поэтому я изменил это на:

def get_songs(website):
    songs = {}
    response = session.get(website)

В-четвертых, вы не можете перебирать словарь с помощью for key, value in songs_dictionary:. Он запрашивает 2 значения, но может распаковать только 1. Чтобы сделать то, что вы пытаетесь, у вас есть 2 варианта:

for key, value in songs_dictionary.items():
        print("Song: " + key)
        print("Artist: " + value)

или

for key in songs_dictionary:
        print("Song: " + key)
        print("Artist: " + songs_dictionary[key])

Я думаю, это все, что я нашел, но полный код здесь:

from bs4 import BeautifulSoup as Bs
import requests

website = "https://soundcloud.com/charts/top?genre=rock&country=all-countries"
session = requests.session()


def get_songs(website):
    songs = {}
    response = session.get(website)
    soup = Bs(response.text, "html.parser")

    print(soup.title.text)

    containers = soup.find_all("section", {"class": "sounds"})
    songs_ranks = containers[0].find_all('li')


    if len(songs_ranks) == 0:
        print("Could not find any containers")

    for element in songs_ranks:

        artist = element.find_all('a')[1].text
        song_name = element.find('a', {'itemprop':'url'}).text

        songs[song_name] = artist

    return songs


def create_file(songs_dictionary):
# Just printing out key&value for now

    for key, value in songs_dictionary.items():
        print("Song: " + key)
        print("Artist: " + value)


toSave = get_songs(website)
create_file(toSave)

выход:

Song: KING
Artist: XXXTENTACION
Song: Queen - Bohemian Rhapsody
Artist: rizky.rilos
Song: áá
©á·áá
¡á¯ (Brit Rock Remix For áá
¡áá
­áá
¢áá
®á¨áá
¦) - BTS
Artist: BTS
Song: XXXTENTACION - NUMB
Artist: conrad foxx
Song: In The End
Artist: LINKIN_PARK
Song: I Write Sins Not Tragedies
Artist: Panic! At The Disco
Song: Man Upon The Hill
Artist: Stars and Rabbit
Song: Nirvana - Smells like teen spirit
Artist: Rocio Araujo
Song: Nickelback - Rockstar
Artist: Roadrunner USA
Song: xxxtentacion - valentine
Artist: ó  
Song: Zombie
Artist: Bad Wolves
Song: Marília Mendonça â Amante Não Tem Lar
Artist: Sertanejo Repost
Song: sleep thru ur alarms
Artist: Lontalius
Song: Angel With A Shotgun
Artist: NightCore
Song: Nightcore - My Demons
Artist: NightCore
Song: Armada - Harusnya Aku
Artist: DJCantik.com
Song: Dont Stop Me Now - Queen
Artist: Zinay Hernandez
Song: Sing To Me feat. Karen O
Artist: waltermartinmusic
Song: Everytime
Artist: boy pablo
Song: Tongue Tied - Grouplove
Artist: Atlantic Records
Song: For Beginners
Artist: M. Ward
Song: This Is Gospel
Artist: Panic! At The Disco
Song: Skillet - Hero
Artist: Warner Music Nashville
Song: Wonderwall - Oasis
Artist: Florian.N.
Song: High Hopes - Panic! At the disco
Artist: IrisDH
Song: Another One Bites The Dust (Remastered 2011)
Artist: Queen
Song: Panic! At The Disco - Bohemian Rhapsody (from Suicide Squad: The Album) (Audio)
Artist: Panic! At The Disco
Song: Killer Queen (Remastered 2011)
Artist: Queen
Song: Blue Bird-Naruto Shippuden 3rd Opening Theme
Artist: flaviogomes23
Song: Virzha-tentang rindu mp3
Artist: Arjuna Bilal
Song: Tipe-X - Mawar Hitam
Artist: Tora Loaadiing
Song: Lolot - Galungan Lan Kuningan
Artist: I Made Suwita
Song: Red Hot Chili peppers - Californication
Artist: arthyum
Song: Nickelback - How You Remind Me
Artist: Roadrunner USA
Song: 2004 Green Day "Boulevard of broken dreams" Vinyl rip
Artist: Collin Codeïne
Song: Zé Neto E Cristiano -  Seu Polícia (DVD Zé Neto E Cristiano Ao Vivo Em São José Do Rio Preto)
Artist: Sertanejo universitario (2018)
Song: Pink Floyd - Wish You Were Here
Artist: Ulviyya Ali
Song: Apocalypse
Artist: Cigarettes After Sex
Song: Linkin Park - In The End
Artist: ALLMusic
Song: Come As You Are
Artist: Nirvana
Song: Avenged Sevenfold - Dear God
Artist: Malik Hamza Sajjad
Song: Kaleo - Way Down We Go
Artist: AminAshkan
Song: Ya Qurban, Khumariyaan, Coke Studio Season 11, Episode 7
Artist: CokeStudio
Song: IDOL (Korean classical music ver.)_2018MMA VER.
Artist: Atm Soo
Song: Gym Best Music For Workout vol 2
Artist: Gym Best MusicFor Workout
Song: Do I Wanna Know? - Arctic Monkeys
Artist: Teenage Kicks.
Song: Um44k - Nossa Música âªâ«
Artist: Portal do Rap
Song: Nanatsu No Taizai (The Seven Deadly Sins) Anime OST - Perfect Time (POWER SONG)
Artist: cobritsa
Song: Tipe X - Genit
Artist: Hilmie CintaSederhana
Song: Kodaline - All I want - Acoustic Performance
Artist: Andy Wells 1
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...