HTML Scraping [파이썬 웹 스크래핑 간단 메뉴얼]

 

HTML Scraping

Web Scraping

Web sites are written using HTML, which means that each web page is a structured document. Sometimes it would be great to obtain some data from them and preserve the structure while we’re at it. Web sites don’t always provide their data in comfortable formats such as csv or json.

This is where web scraping comes in. Web scraping is the practice of using a computer program to sift through a web page and gather the data that you need in a format most useful to you while at the same time preserving the structure of the data.

lxml and Requests

lxml is a pretty extensive library written for parsing XML and HTML documents very quickly, even handling messed up tags in the process. We will also be using the Requests module instead of the already built-in urllib2 module due to improvements in speed and readability. You can easily install both using pip install lxml and pip install requests.

Let’s start with the imports:

from lxml import html
import requests

Next we will use requests.get to retrieve the web page with our data, parse it using the html module and save the results in tree:

page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(page.content)

(We need to use page.content rather than page.text because html.fromstring implicitly expects bytes as input.)

tree now contains the whole HTML file in a nice tree structure which we can go over two different ways: XPath and CSSSelect. In this example, we will focus on the former.

XPath is a way of locating information in structured documents such as HTML or XML documents. A good introduction to XPath is on W3Schools .

There are also various tools for obtaining the XPath of elements such as FireBug for Firefox or the Chrome Inspector. If you’re using Chrome, you can right click an element, choose ‘Inspect element’, highlight the code, right click again and choose ‘Copy XPath’.

After a quick analysis, we see that in our page the data is contained in two elements - one is a div with title ‘buyer-name’ and the other is a span with class ‘item-price’:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

<div title="buyer-name">Carson Busses</div>
<span class="item-price">.95</span>

Knowing this we can create the correct XPath query and use the lxml xpath function like this:

#This will create a list of buyers:
buyers = tree.xpath('//div[@title="buyer-name"]/text()')
#This will create a list of prices
prices = tree.xpath('//span[@class="item-price"]/text()')

Let’s see what we got exactly:

print 'Buyers: ', buyers
print 'Prices: ', prices
Buyers:  ['Carson Busses', 'Earl E. Byrd', 'Patty Cakes',
'Derri Anne Connecticut', 'Moe Dess', 'Leda Doggslife', 'Dan Druff',
'Al Fresco', 'Ido Hoe', 'Howie Kisses', 'Len Lease', 'Phil Meup',
'Ira Pent', 'Ben D. Rules', 'Ave Sectomy', 'Gary Shattire',
'Bobbi Soks', 'Sheila Takya', 'Rose Tattoo', 'Moe Tell']

Prices:  ['.95', '.37', '.26', '.25', '.25',
'.99', '.57', '.49', '.47', '.86', '.11',
'.98', '.27', '.50', '.85', '.26', '17072.68',
'.00', '4.07', '.09']

Congratulations! We have successfully scraped all the data we wanted from a web page using lxml and Requests. We have it stored in memory as two lists. Now we can do all sorts of cool stuff with it: we can analyze it using Python or we can save it to a file and share it with the world.

Some more cool ideas to think about are modifying this script to iterate through the rest of the pages of this example dataset, or rewriting this application to use threads for improved speed.

 

 

[출처] http://docs.python-guide.org/en/latest/scenarios/scrape/

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
22 [파이썬으로 웹 크롤러 만들기] 크롤링 시작하기(2/3) file 졸리운_곰 2017.02.16 709
21 [파이썬으로 웹 크롤러 만들기] 크롤링 시작하기(1/3) file 졸리운_곰 2017.02.16 772
20 Python으로 RESTAPI 이용하기 졸리운_곰 2017.02.11 462
19 [Python] 네이버 블로그 xml-rpc 클라이언트 만들기 – 1 졸리운_곰 2017.01.07 563
18 웹 크롤링 by python file 졸리운_곰 2016.12.14 1451
17 [Scrapy] 웹사이트 크롤링해서 DB 저장 하기(분양정보수집사례) file 졸리운_곰 2016.11.29 740
16 [Scrapy] 웹사이트 크롤링해서 파일 저장 하기(분양정보수집사례) file 졸리운_곰 2016.11.29 1721
15 [python] BeautifulSoup으로 웹에 있는 데이터 긁어오기 졸리운_곰 2016.11.15 586
14 [python] httplib — HTTP protocol client¶ 졸리운_곰 2016.11.15 548
13 python torrent 자동 다운로드 : How to automatically search and download torrents with Python and Scrapy 졸리운_곰 2016.11.02 875
12 Apache와 Python 연동하기 졸리운_곰 2016.10.16 1612
» HTML Scraping [파이썬 웹 스크래핑 간단 메뉴얼] 졸리운_곰 2016.07.30 766
10 Anonymous Web Scraping using Python and Tor file 졸리운_곰 2016.05.04 1284
9 Using TOR with Python file 졸리운_곰 2016.05.04 1911
8 Crawling anonymously with Tor in Python 졸리운_곰 2016.05.04 542
7 scrapy : 크롤링 해보기 file 졸리운_곰 2016.04.21 719
6 Python으로 공공데이터 오픈 API 활용하기 졸리운_곰 2016.01.14 1225
5 Title: HTML Scraper using pyhton 졸리운_곰 2015.09.01 400
4 위대한 LG SMART SMA LG 빅데이터 플랫폼 [파이썬 웹 크롤러] 웹 스파이더 file 졸리운_곰 2015.05.02 1154
3 위대한 LG SMART SMA LG 빅데이터 플랫폼 [소셜 웹 마이닝] 데이터 마이닝, 웹 마이닝 file 졸리운_곰 2015.05.02 775
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED