国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Python網絡爬蟲(1)--url訪問及參數設置

2019-11-14 17:22:32
字體:
來源:轉載
供稿:網友

環境:Python2.7.9 / Sublime Text 2 / Chrome

1.url訪問,直接調用urllib庫函數即可

import urllib2url='http://www.baidu.com/'response = urllib2.urlopen(url)html=response.read()PRint html

2.帶參數的訪問,以baidu搜索功能為例

使用Chrome瀏覽器訪問效果,Chrome搜索引擎設置為baidu,地址欄中輸入test,效果如下:

image

可以看到baidu搜索的url為 https://www.baidu.com/s?ie=UTF-8&wd=test

修改代碼,增加訪問參數

# coding=utf-8import urllibimport urllib2#url地址url='https://www.baidu.com/s'#參數values={        'ie':'UTF-8',        'wd':'test'           }#進行參數封裝data=urllib.urlencode(values)#組裝完整urlreq=urllib2.Request(url,data)#訪問完整urlresponse = urllib2.urlopen(req)html=response.read()print html

運行代碼,(Sublime Text 如果出現Decode error,需要將Python.sublime-build設置為"encoding": "utf-8")得到結果為

image

提示訪問頁面不存在,這個時候需要考慮一下訪問方式的問題。使用Chrome開發者工具,監測Network,確定訪問方式為GET

 

urllib2.Request(url,data) 訪問方式為POST方式,改用GET方式進行嘗試,需要手動組裝URL,更改代碼為

# coding=utf-8import urllibimport urllib2#url地址url='https://www.baidu.com/s'#參數values={        'ie':'UTF-8',        'wd':'test'           }#進行參數封裝data=urllib.urlencode(values)#組裝完整url#req=urllib2.Request(url,data)url=url+'?'+data#訪問完整url#response = urllib2.urlopen(req)response = urllib2.urlopen(url)html=response.read()print html

再次運行,獲得結果為

image

https發生了重定向,需要改用http

# coding=utf-8import urllibimport urllib2#url地址#url='https://www.baidu.com/s'url='http://www.baidu.com/s'#參數values={        'ie':'UTF-8',        'wd':'test'           }#進行參數封裝data=urllib.urlencode(values)#組裝完整url#req=urllib2.Request(url,data)url=url+'?'+data#訪問完整url#response = urllib2.urlopen(req)response = urllib2.urlopen(url)html=response.read()print html

再次運行,可實現正常訪問

image

 

http://leettest.com/blog/

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 称多县| 手游| 鸡东县| 兴化市| 兴文县| 清水县| 宜宾县| 屏东市| 措勤县| 乌兰察布市| 青阳县| 大足县| 昂仁县| 石渠县| 清水县| 芦山县| 津市市| 新余市| 饶阳县| 山阳县| 康平县| 章丘市| 岑巩县| 巢湖市| 合阳县| 周至县| 新乡县| 莫力| 大城县| 盐边县| 大关县| 隆德县| 马龙县| 峨眉山市| 白水县| 洪洞县| 石河子市| 罗田县| 湟源县| 延吉市| 甘洛县|