1. 程式人生 > >python爬蟲系列(1.1-urllib模組常用方法的介紹)

python爬蟲系列(1.1-urllib模組常用方法的介紹)

一、關於urllib中常用方法的介紹

  • 1、urlopen網路請求

    urlopen方法是網路請求的方法,預設是get請求,如果傳遞了datapost請求

    from urllib import request
    
    if __name__ == "__main__":
        response = request.urlopen('http://www.baidu.com')
        print(response.read())
    
  • 2、urlretrieve下載檔案

    from urllib import request
    
    if __name__ == "__main__":
        # 下載整個網頁
    request.urlretrieve('http://www.baidu.com', 'baidu.html') # 下載圖片 request.urlretrieve('http://www.baidu.com/img/bd_logo1.png', 'baidu.png')

二、關於編碼的處理

  • 1、urlencode將字典型別資料轉換為parsed模式

    from urllib import parse
    
    if __name__ == "__main__":
        dict1 = {
            "name": "hello",
            "age": "20"
    , "gender": "man" } re = parse.urlencode(dict1) print(re) # name=hello&age=20&gender=man
  • 2、parse_qsparse_qsl反序列化

    from urllib import parse
    
    if __name__ == "__main__":
        dict1 = {
            "name": "hello",
            "age": "20",
            "gender": "man"
        }
        re = parse.
    urlencode(dict1) print(re) print(parse.parse_qs(re))

三、切割url的方法

  • 1、urlspliturlparse方法

    from urllib import request, parse
    
    if __name__ == "__main__":
        url = 'http://www.baidu.com?name=hello&age=20'
        print(parse.urlsplit(url))
        print(parse.urlparse(url))
    
    # 輸出
    # SplitResult(scheme='http', netloc='www.baidu.com', path='', query='name=hello&age=20', fragment='')
    # ParseResult(scheme='http', netloc='www.baidu.com', path='', params='', query='name=hello&age=20', fragment='')