python_爬蟲_模組

來源:互聯網
上載者:User

標籤:隨機   res   encoding   post請求   ons   def   儲存   重複   串連數   

import pymysqlfrom urllib import request,parsefrom urllib.error import HTTPError,URLErrordef main(url,headers=None,data=None): # 調用函數    if not data:        return get_response(url,headers=headers)    else:        return get_response(url,headers=headers,data=data)def get_response(url,data=None,headers=None):    if not headers:        headers = {‘User-Agent‘:get_agent()}    try:        if data:            data = parse.urlencode(data)            data = bytes(data,encoding=‘utf-8‘)            req = request.Request(url, data=data, headers=headers)        else:            req = request.Request(url,headers=headers)        response = request.urlopen(req)        data = response.read().decode()        return data # 返回資料    except HTTPError as e: # 總的錯誤資訊,不適合用於調試        print(e)    except URLError as e:        print(e)def get_agent(table=None): # 提前使用fake_useragent模組產生的要求標頭,儲存在資料庫中,避免出現問題無法調用fake_useragent模組    table = ‘p_useragent‘    conn = pymysql.connect(‘127.0.0.1‘, ‘root‘, ‘123456‘, ‘PaChong‘, charset=‘utf8‘)    cursor = conn.cursor() # 串連資料庫,隨機調用要求標頭    sql = ‘SELECT * FROM {} WHERE id >= ((SELECT MAX(Id) FROM {})-(SELECT MIN(Id) FROM {})) * RAND() + (SELECT MIN(Id) FROM p_useragent)  LIMIT 1‘.format(        table, table, table)    rwo = cursor.execute(sql)    useragent = cursor.fetchall()[0][1]    return useragentif __name__ == ‘__main__‘:    url = ‘http://fanyi.baidu.com/sug‘    data = {‘kw‘:‘中國‘}    import json    res = json.loads(main(url,data=data))    print(res)    # url = ‘http://www.baidu.com‘    # res = main(url)    # print(res)

正常情況下,每寫一個爬蟲,都需要執行分析->請求->響應->下載(儲存)的流程,但諸多功能,其實都是在重複造輪子,比如請求、調用要求標頭、post請求data值,可以將這些功能寫到一個py檔案裡,這樣再寫其他爬蟲檔案時, 直接調用,就可以略過輸入要求標頭、post傳參轉碼等諸多操作。

python_爬蟲_模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.