очистите детали фильма с помощью BS4

#python #pandas #beautifulsoup

#python #панды #beautifulsoup

Вопрос:

Очистите «http://fresco-movies.surge.sh /» и получите подробную информацию о фильме и добавьте data.csv

Я должен очистить данные, такие как название фильма, продолжительность, жанр, рейтинг, описание, режиссер и голоса, с веб-сайта и сохранить их в data.csv.

Пожалуйста, помогите мне с кодом

  from bs4 import BeautifulSoup
import requests
url = "http://fresco-movies.surge.sh/"
req = requests.get(url)
soup = BeautifulSoup(req.content, 'html.parser')
print(soup)
 

Комментарии:

1. Отлично. В чем вопрос?

2. Привет @Mayank нужна помощь с кодом .. Пожалуйста

3. Я знаю, как это сделать, используя selenium, но не с bs4. В качестве решения требуется только с BS4

4. Я бы рекомендовал опубликовать фрагмент, который использует Selenium , потому что нужно знать Xpath / Jquery, который необходимо использовать…

5. Привет @YannisP. у меня нет..

Ответ №1:

Это прямая навигация по HTML-документу

 from bs4 import BeautifulSoup
import requests
url = "http://fresco-movies.surge.sh/"
req = requests.get(url)
soup = BeautifulSoup(req.content, 'html.parser')
names = []
for m in soup.find_all("div", class_="row"):
    names.append({"name":m.find("a").text,
                 "director":m.find("div", class_="ratings-bar").find("a").text,
                 "votes":m.find("div", class_="ratings-bar").find("p", class_="sort-num_votes-visible").find_all("span")[1].text,
                 "certificate":m.find("span", class_="certificate"),
                 "runtime":m.find("span", class_="runtime"),

                 })
    
print(pd.DataFrame(names).head(5).to_string(index=False))

 

вывод

                                           name              director    votes certificate    runtime
                      The Shawshank Redemption        Frank Darabont  2033239       [9.3]  [142 min]
                                 The Godfather  Francis Ford Coppola  1394179       [9.2]  [175 min]
                               The Dark Knight     Christopher Nolan  2001026       [9.0]  [152 min]
                        The Godfather: Part II  Francis Ford Coppola   966187       [9.0]  [202 min]
 The Lord of the Rings: The Return of the King         Peter Jackson  1447736       [8.9]  [201 min]
 

Ответ №2:

Я намеренно оставил для вас некоторую работу, но этого должно быть достаточно, чтобы вы начали.

 from bs4 import BeautifulSoup

html = '''
<div class="lister-item-content">
    <h3 class="lister-item-header">
        <span class="lister-item-index unbold text-primary"></span>
        <a href="http://127.0.0.1:5000/#">The Shawshank Redemption</a>
    </h3>
    <p class="text-muted ">
        <span class="certificate">9.3</span>
        <span class="ghost">|</span> 
        <span class="runtime">142 min</span>
        <span class="ghost">|</span> 
        <span class="genre">Drama</span>
    </p>
    <div class="ratings-bar">
        <p class="text-muted">Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.</p>
        <p class="">
            Director:
            <a href="http://127.0.0.1:5000/#">Frank Darabont</a>
        </p>
        <p class="sort-num_votes-visible">
            <span class="text-muted">Votes:</span>
            <span name="nv" data-value="41436">2033239</span>
        </p>
    </div>
</div>
'''

soup = BeautifulSoup(html, 'html.parser')
for item in soup.select('div.lister-item-content'):
    title = item.select_one('h3.lister-item-header').text.strip()
    rating = item.select_one('span.certificate').text.strip()
    description_para = item.select_one('div.ratings-bar > p:first-child')
    description = description_para.text.strip()
    director_para = description_para.find_next_sibling('p')
    director = description_para.find_next_sibling('p').a.text.strip()
 

Если вы не можете разобраться в остальном, обратитесь к документам BeautifulSoup .