CoderCastrov logo
CoderCastrov
Питон

Как выполнить парсинг данных с использованием Python

Как выполнить парсинг данных с использованием Python
просмотров
2 мин чтение
#Питон
Table Of Content

Шаг первый

Выполните "Инспектировать элемент" на веб-странице, например https://books.toscrape.com/

Do an Inspect element on the web for example https://books.toscrape.com/

A) Сначала найдите элемент, который отображает место изображения книги

First look for the element that shows the place of the book image

B) Затем найдите элемент заголовка

Second look for the title element

C) Затем найдите элемент раздела рейтинга

Third, look for the elements the rating section

D) Затем найдите место цены

Fourth, find in the location of the price

Если вы уже знаете расположение всех элементов выше, тогда мы будем парсить данные на монитор

If you already know the location of everything above, ​​​​​​​then we will scrape the data to the monitor

from bs4 import BeautifulSoup
import requests
# import pandas as pd

def convertR(rtg):
    if rtg == ['star-rating', 'One']:
        rtg = '1'
        return rtg
    elif rtg == ['star-rating', 'Two']:
        rtg = '2'
        return rtg
    elif rtg == ['star-rating', 'Three']:
        rtg = '3'
        return rtg
    elif rtg == ['star-rating', 'Four']:
        rtg = '4'
        return rtg
    else:
        rtg = '5'
        return rtg

try :
    print('')
    print('Starting Scrapping...')
    print('')
    # data=[]
    for page in range(1, 3):
        html = requests.get('http://books.toscrape.com/catalogue/page-'+str(page)+'.html')
        html_soup = BeautifulSoup(html.content, 'html.parser')
        data_all = html_soup.find_all('article', class_ = 'product_pod')
        print('-------------------------------')
        print('~ ~ ~ Scrapping Page Ke-' + str(page) + ' ~ ~ ~')
        print('-------------------------------')
        for b in data_all:

            dataGbr = b.find('img', class_='thumbnail')
            dataGambar = dataGbr.get('src')

            dataJdl = b.find('h3')
            dataJdl2 = dataJdl.find('a')
            dataJudul = dataJdl2.get('title')

            dataRtg = b.find('p')
            dataRating = dataRtg.get('class')
            Rating = convertR(dataRating)

            dataHarga = b.find('p', class_ = 'price_color').text

            print('')
            print('Gambar : ' + str(dataGambar.replace('..','http://books.toscrape.com')))
            print('Judul  : ' + str(dataJudul))
            print('Rating : ' + str(Rating))
            print('Harga  : ' + dataHarga.replace('£',''))
            print('')

    #         data.append({
    #             'Gambar':dataGambar,
    #             'Judul':dataJudul,
    #             'Rating':Rating,
    #             'Harga':dataHarga.replace('£','')
    #         })
    # df = pd.DataFrame(data)
    # df.to_csv('Data_Buku.csv', encoding='utf-8')
    print('Scrapping Success...')

except Exception as err :
    ('')

Введите и запустите приведенный выше код, используя язык программирования Python

Type and run the above code using the python programming language

Затем результат отображается следующим образом

Then the results are displayed as follows

result

Чтобы отобразить 50 страниц, вам нужно выполнить парсинг данных со всех существующих страниц с 1 по 50

To display 50 pages, you have to scrape data over all existing pages from 1–50 pages

 for page in range(1, 51):

Результат парсинга ниже

The result of the scrape is below

result

Вот и все, надеюсь, что эти знания будут полезны, до свидания