
В Інтернеті є більше інформації, ніж будь-яка людина може сприйняти за все життя. Вам потрібен не доступ до цієї інформації, а масштабований спосіб її збору, організації та аналізу.
Вам потрібно зішкріб з Інтернету.
Веб-скрапінг автоматично витягує дані та подає їх у форматі, який ви можете легко зрозуміти. У цьому навчальному посібнику ми зосередимося на його застосуванні на фінансовому ринку, але веб-скрапінг може бути використаний у найрізноманітніших ситуаціях.
Якщо ви завзятий інвестор, отримувати ціни на закриття щодня може бути неприємно, особливо коли потрібна інформація знаходиться на кількох веб-сторінках. Ми спростимо витяг даних, створивши веб-скрепер для автоматичного отримання фондових індексів з Інтернету.

Починаємо
Ми збираємось використовувати Python як нашу мову скрапування разом із простою і потужною бібліотекою BeautifulSoup.
- Для користувачів Mac, Python попередньо встановлений в OS X. Відкрийте термінал і введіть
python --version
. Ви повинні побачити, що ваша версія python - 2.7.x. - Для користувачів Windows, будь ласка, встановіть Python через офіційний веб-сайт.
Далі нам потрібно отримати бібліотеку BeautifulSoup, використовуючи pip
інструмент управління пакетами для Python.
У терміналі введіть:
easy_install pip pip install BeautifulSoup4
Примітка : Якщо вам не вдається виконати наведений вище командний рядок, спробуйте додати sudo
перед кожним рядком.
Основи
Перш ніж ми почнемо переходити до коду, давайте розберемося з основами HTML та деякими правилами вискоблювання.
Теги HTML
Якщо ви вже розумієте HTML-теги, сміливо пропускайте цю частину.
First Scraping
Hello World
Це основний синтаксис веб-сторінки HTML. Кожен обслуговує блок усередині веб-сторінки:
1 .: Документи HTML повинні починатися з декларації типу.
2. Документ HTML міститься між і
.
3. Мета і сценарій оголошення HTML-документа знаходиться між і
.
4. Видима частина документа HTML знаходиться між і
тегами.
5. Заголовки заголовків визначаються символом

Original text
через
теги.
теги.6. Абзаци визначаються символом
Other useful tags include
for hyperlinks,
for tables,
for table rows, and
для стовпців таблиці. Крім того, HTML-теги іноді мають Для отримання додаткової інформації щодо тегів HTML, ідентифікатора та класу, будь ласка, зверніться до W3Schools Tutorials. Правила вишкрібання
Огляд сторінкиВізьмемо для прикладу одну сторінку з веб-сайту Bloomberg Quote. Як хтось, хто стежить за фондовим ринком, ми хотіли б отримати назву індексу (S&P 500) та його ціну на цій сторінці. Спочатку клацніть правою кнопкою миші та відкрийте інспектор браузера, щоб перевірити веб-сторінку. ![]() Спробуйте навести курсор на ціну, і ви зможете побачити синє поле навколо нього. Якщо клацнути на ньому, відповідний HTML буде вибраний на консолі браузера. ![]() From the result, we can see that the price is inside a few levels of HTML tags, which is Similarly, if you hover and click the name “S&P 500 Index”, it is inside .![]() Now we know the unique location of our data with the help of Jump into the CodeNow that we know where our data is, we can start coding our web scraper. Open your text editor now! First, we need to import all the libraries that we are going to use.
Next, declare a variable for the url of the page.
Then, make use of the Python urllib2 to get the HTML page of the url declared.
Finally, parse the page into BeautifulSoup format so we can use BeautifulSoup to work on it.
Now we have a variable, Remember the unique layers of our data? BeautifulSoup can help us get into these layers and extract the content with
After we have the tag, we can get the data by getting its
Similarly, we can get the price too.
When you run the program, you should be able to see that it prints out the current price of the S&P 500 Index. ![]() Export to Excel CSVNow that we have the data, it is time to save it. The Excel Comma Separated Format is a nice choice. It can be opened in Excel so you can see the data and process it easily. But first, we have to import the Python csv module and the datetime module to get the record date. Insert these lines to your code in the import section.
At the bottom of your code, add the code for writing data to a csv file.
Now if you run your program, you should able to export an ![]() So if you run this program everyday, you will be able to easily get the S&P 500 Index price without rummaging through the website! Going Further (Advanced uses)Multiple Indices So scraping one index is not enough for you, right? We can try to extract multiple indices at the same time. First, modify the
Then we change the data extraction code into a
Also, modify the saving section to save data row by row.
Rerun the program and you should be able to extract two indices at the same time! Advanced Scraping TechniquesBeautifulSoup is simple and great for small-scale web scraping. But if you are interested in scraping data at a larger scale, you should consider using these other alternatives:
Adopt the DRY Method![]() DRY stands for “Don’t Repeat Yourself”, try to automate your everyday tasks like this person. Some other fun projects to consider might be keeping track of your Facebook friends’ active time (with their consent of course), or grabbing a list of topics in a forum and trying out natural language processing (which is a hot topic for Artificial Intelligence right now)! If you have any questions, please feel free to leave a comment below. References //www.gregreda.com/2013/03/03/web-scraping-101-with-python/ //www.analyticsvidhya.com/blog/2015/10/beginner-guide-web-scraping-beautiful-soup-python/ This article was originally published on Altitude Labs’ blog and was written by our software engineer, Leonard Mok. Altitude Labs is a software agency that specializes in personalized, mobile-first React apps. |