python爬蟲抓取信息-urllib

自己晚上寫的 本來抓取的是匯率 沒寫完 唉 路還長 繼續走

import requests
import urllib.request
import urllib.request
import re
import datetime


def get_headers():
    '''定義請求頭 換着請求頭進行爬取'''
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
    }
    return headers
def get_ip():
    '''代理ip 換着地址進行爬取信息'''
    pass

def grab_info():
    '''抓取地址'''
    url = 'http://fx.cmbchina.com/hq/'
    return url
def get_url_address(url):
    '''處理請求地址,或者翻頁
    返回的信息可以是json數據
    使用代理ip時要跟換方法使用 可以提前寫好
    '''
    headers = get_headers()
    request = urllib.request.Request(url, headers=headers)
    return request

proxy_handler = urllib.request.ProxyHandler({'http': '120.32.208.16:8118'})
opener = urllib.request.build_opener(proxy_handler)


def get_html(request):
    '''進行響應,獲取數據'''
    repsonse = urllib.request.urlopen(request)
    html = repsonse.read().decode('utf-8')
    return html
def handle_data(html):
    '''利用xpath re 進行解析'''
    need_data = dict()

    print(html)


def need_info():
    '''存儲數據 可以存入表格等 重新調取數據'''
    pass

def main():
    '''主程序 可以設置死循環 來進行不斷抓取數據'''
    url = grab_info()
    request = get_url_address(url=url)
    html = get_html(request =request)
    handle_data(html = html)


if __name__ == '__main__':
    start_time = datetime.datetime.now()
    main()
    end_time = datetime.datetime.now()
    print('爬取時間{time}'.format(time = end_time-start_time))



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章