爬虫初窥

静态爬虫和动态爬虫

静态爬虫:页面数据的展示不依靠js等和后台的交互。
动态爬虫:页面的数据需要通过js,ajax等交互才能获得(完整获得)。

静态爬虫

通过使用urllib,beautifulsoup等工具对下载的页面进行xml节点的解析。

一个例子(爬取自己的博客的所有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'

# 插入一行,行数据使用list来表示
@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条数据抓取完毕,正在唤醒save')
        yield

    if posts is not None:
        # 进入下一个页面进行抓取
        next_url = '%s%s' % (entry_url, bsobj.find(class_='pager').find('a').attrs['href'])
        print('开始抓取下一个页面: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()

这种静态爬虫比较简单,只要分析清楚页面结构就可以了

注意点:和协程配合使用;把需要捕获的异常尽量写全,整体代码的逻辑清晰;使用mobile版本的地址进行更快的解析。

动态爬虫

比价麻烦,在没有学习scrapy框架之前(觉得需要慢慢来自己摸索的前进~),我选择了selenium进行数据的爬取。

这是一个例子的片段:

@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 = []
        # 航班号
        flight_id = child.get_attribute('id').strip()
        if pattern.search(flight_id) is not None:
            # 计划机型
            flight_type = child.find_element_by_xpath('table/tbody/tr/td[1]/div[2]/span').text.strip()
            # 起飞时刻
            flight_dtime = child.find_element_by_xpath('table/tbody/tr/td[2]/div[1]/strong').text.strip()
            # 起飞机场
            flight_dport = child.find_element_by_xpath('table/tbody/tr/td[2]/div[2]').text.strip()
            # 到达时刻
            flight_atime = child.find_element_by_xpath('table/tbody/tr/td[4]/div[1]/strong').text.strip()
            # 到达时刻
            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()
            # 最低价格
            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

从携程上爬取航班的价格情况。

技术点

****XPATH****的使用方法:

selenium最常见的解析节点的方法就是使用xpath进行解析。

//*[@id="reSearchForm"]/div/div[3]/input

找到文档中名为“reSearchForm”的节点,并逐步向下解析。其中类似”input[number]“中的number的起始数字是”1“,这点需要注意。

****time.sleep()****

在经过类似于”click()“等事件之后,需要主动的进行time.sleep()的处理。

****页面的拖拽****

有些js需要经过页面的拖拽才能从后台抓取数据,需要代码中进行拖拽,例如:

for i in range(2):
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(5)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容