Python 幾種爬蟲的方法
一、使用Requests庫
1.1安裝Requests庫
pip install Requests
1.2實例:
import Requests
r = Requests.get(url)
print r.text
print r.status_code
傳遞URL參數
import requests
key_dict = {'key1':'value1','key2':'value2'}
r = requests.get(url,params=key_dict)
定制請求頭
import requests
headers = {"User-Agent":......,
"Host":......}
r = requests.get(url,headers=headers)
print (“響應狀態碼:”,r.status_code)
二、使用selenium模擬瀏覽器
2.1安裝selenium
pip install selenium
示例:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get(url)
注:使用selenium模擬瀏覽器時,需要下載對應的驅動,例如:火狐:需要下載geckodriver.exe;谷歌:需要下載chromdriver.exe;IE:需要下載IEDriverServer.exe ;下載好驅動后,放在相應的瀏覽器安裝目錄下,並將其加入環境變量
遇到的問題:
1.Python2和3中'ascii' codec can't decode position 0: ordinal not in range(128)
python2:
在開頭加上
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
python3:
x = pickle.load(open("./data/coco/word2vec.p","rb"),encoding='bytes')
2.使用demjson
pip install demjson
demjson.encode --將對象轉換json
demjsonl.decode --將json轉化為對象
3.print ()
使用
i = cool
print("中文測試:" + i )
使用上述方法容易亂碼
可以使用:
print (“中文測試 %s”) % i
解決