靜態(tài)爬蟲(chóng)和動(dòng)態(tài)爬蟲(chóng)
靜態(tài)爬蟲(chóng):頁(yè)面數(shù)據(jù)的展示不依靠js等和后臺(tái)的交互帅刀。
動(dòng)態(tài)爬蟲(chóng):頁(yè)面的數(shù)據(jù)需要通過(guò)js让腹,ajax等交互才能獲得(完整獲得)。
靜態(tài)爬蟲(chóng)
通過(guò)使用urllib扣溺,beautifulsoup等工具對(duì)下載的頁(yè)面進(jìn)行xml節(jié)點(diǎn)的解析骇窍。
一個(gè)例子(爬取自己的博客的所有blog):
#!/usr/bin/env python3
# coding:utf-8
from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
import asyncio
from openpyxl import Workbook
import datetime
wb = Workbook()
worksheet = wb.active
entry_url = 'http://www.radasm.me:8080'
# 插入一行,行數(shù)據(jù)使用list來(lái)表示
@asyncio.coroutine
def save_one_row(ws_name):
while True:
l = yield
if l is not None:
l.insert(0, datetime.datetime.now())
worksheet.append(l)
print('正在保存中锥余。腹纳。。')
wb.save(ws_name)
pre_url = 'http://www.radasm.me:8080'
@asyncio.coroutine
def begin_scrap(sa, url):
try:
html = urlopen(url)
except HTTPError as e:
print(e)
bsobj = BeautifulSoup(html)
posts = bsobj.find_all(class_='post')
for post in posts:
l = []
blog_href = post.find(class_='title').find('a').attrs['href']
blog_name = post.find(class_='title').find('a').get_text()
blog_time = post.find(class_='time').find(class_='date').get_text()
l.append(blog_time)
l.append(blog_name)
l.append('%s%s' % (pre_url, blog_href))
sa.send(l)
print('1條數(shù)據(jù)抓取完畢驱犹,正在喚醒save')
yield
if posts is not None:
# 進(jìn)入下一個(gè)頁(yè)面進(jìn)行抓取
next_url = '%s%s' % (entry_url, bsobj.find(class_='pager').find('a').attrs['href'])
print('開(kāi)始抓取下一個(gè)頁(yè)面:next is %s' % next_url)
begin_scrap(sa, next_url)
sa = save_one_row('haha.xls')
sa.send(None)
loop = asyncio.get_event_loop()
loop.run_until_complete(begin_scrap(sa, entry_url))
loop.close()
這種靜態(tài)爬蟲(chóng)比較簡(jiǎn)單嘲恍,只要分析清楚頁(yè)面結(jié)構(gòu)就可以了
注意點(diǎn):和協(xié)程配合使用;把需要捕獲的異常盡量寫全雄驹,整體代碼的邏輯清晰佃牛;使用mobile版本的地址進(jìn)行更快的解析。
動(dòng)態(tài)爬蟲(chóng)
比價(jià)麻煩医舆,在沒(méi)有學(xué)習(xí)scrapy框架之前(覺(jué)得需要慢慢來(lái)自己摸索的前進(jìn)~)俘侠,我選擇了selenium進(jìn)行數(shù)據(jù)的爬取象缀。
這是一個(gè)例子的片段:
@asyncio.coroutine
def begin(save):
coun = 2
driver = webdriver.Firefox()
driver.get(entry_url)
driver.find_element_by_xpath('//*[@id="reSearchForm"]/div/div[3]/input').click()
time.sleep(2)
for i in range(2):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(5)
flights = driver.find_element_by_xpath('//*[@id="J_flightlist2"]')
children = flights.find_elements_by_xpath('div')
print(children)
for child in children:
l = []
# 航班號(hào)
flight_id = child.get_attribute('id').strip()
if pattern.search(flight_id) is not None:
# 計(jì)劃?rùn)C(jī)型
flight_type = child.find_element_by_xpath('table/tbody/tr/td[1]/div[2]/span').text.strip()
# 起飛時(shí)刻
flight_dtime = child.find_element_by_xpath('table/tbody/tr/td[2]/div[1]/strong').text.strip()
# 起飛機(jī)場(chǎng)
flight_dport = child.find_element_by_xpath('table/tbody/tr/td[2]/div[2]').text.strip()
# 到達(dá)時(shí)刻
flight_atime = child.find_element_by_xpath('table/tbody/tr/td[4]/div[1]/strong').text.strip()
# 到達(dá)時(shí)刻
flight_aport = child.find_element_by_xpath('table/tbody/tr/td[4]/div[2]').text.strip()
# 幣種
money_type = child.find_element_by_xpath('table/tbody/tr/td[8]/span/dfn').text.strip()
# 最低價(jià)格
flight_lprice = child.find_element_by_xpath('table/tbody/tr/td[8]/span').text.strip()[1:]
price = int(flight_lprice[1:])
# 折扣
discount = price / FULL_PRICE
l.append(flight_id)
l.append(flight_type)
l.append(flight_dtime)
l.append(flight_dport)
l.append(flight_atime)
l.append(flight_aport)
l.append(money_type)
l.append(flight_lprice)
l.append(discount)
save.send(l)
yield
從攜程上爬取航班的價(jià)格情況。
技術(shù)點(diǎn)
****XPATH****的使用方法:
selenium最常見(jiàn)的解析節(jié)點(diǎn)的方法就是使用xpath進(jìn)行解析爷速。
//*[@id="reSearchForm"]/div/div[3]/input
找到文檔中名為“reSearchForm”的節(jié)點(diǎn)央星,并逐步向下解析。其中類似”input[number]“中的number的起始數(shù)字是”1“惫东,這點(diǎn)需要注意莉给。
****time.sleep()****
在經(jīng)過(guò)類似于”click()“等事件之后,需要主動(dòng)的進(jìn)行time.sleep()的處理廉沮。
****頁(yè)面的拖拽****
有些js需要經(jīng)過(guò)頁(yè)面的拖拽才能從后臺(tái)抓取數(shù)據(jù)禁谦,需要代碼中進(jìn)行拖拽,例如:
for i in range(2):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(5)