1. 程式人生 > >python網路程式設計requests和selenium模組

python網路程式設計requests和selenium模組

import requests #需要命令列下pip install requests安裝
req = requests.get("http://httpbin.org/get", headers = {"User-Agent" : "ua"}, proxies = {"http" : "ip:port"}, timeout = 10, verify = False)
#以get方式開啟連結 設定User-Agent為"ua" 設定代理伺服器為"ip:port" 連線超時時間10秒 verify = False不檢測證書
print req.status_code  #返回狀態
print req.
url #返回請求url print req.headers #返回http頭 print req.cookies #返回cookie資訊 print req.text #返回文字形式網頁原始碼 print req.content #返回位元組流形式網頁原始碼

requests模組的使用

from selenium import webdriver                                      #匯入selenium的瀏覽器驅動介面
chrome_options = webdriver.chrome.
options.Options() chrome_options.add_argument('--headless') #後臺模式 prefs = {"profile.managed_default_content_settings.images" : 2} chrome_options.add_experimental_option("prefs",prefs) #不載入圖片 chrome_options.add_argument("user-agent=" + "ua") #設定userAgent為"ua"
chrome_options.add_argument("--proxy-server=http://ip:port") #設定代理為"ip:port" driver = webdriver.Chrome(chrome_options=chrome_options) #根據option獲得一個瀏覽器 driver.set_page_load_timeout(90) #設定頁面載入超時時間90秒 driver.get(u"https://www.baidu.com") #開啟一個連結 driver.save_screenshot("baidu.png") #得到當前網頁的截圖 print driver.title #得到當前網頁的標題 print driver.current_url #得到當前網頁的url print driver.page_source #得到當前網頁的原始碼 driver.find_element_by_id("kw").send_keys("hello world") #得到原始碼中id為kw的物件(搜尋框) 模擬輸入文字"hello world" driver.find_element_by_id("su").click() #得到原始碼中id為su的物件(搜尋按鈕) 模擬單擊 driver.execute_script("window.scrollBy(0, 3000)") #執行一個js指令碼 下翻頁 driver.back() #瀏覽器後退一個頁面 driver.quit() #關閉瀏覽器

使用selenium模組+chromedriver模擬瀏覽器訪問

import chardet
print chardet.detect(str) #當編碼為Unicode時報錯
#TypeError: Expected object of type bytes or bytearray, got: <type 'unicode'>

識別一個字串的編碼型別

import warnings
warnings.filterwarnings("ignore") #忽略警告資訊

忽略其它模組警告資訊

# -*- coding: utf-8 -*-
import codecs
fp = file("a.txt", "r") #utf8帶BOM檔案
str = fp.read()
fp.close()
print str
print str.replace(codecs.BOM_UTF8, "") #消除檔案UTF8格式的BOM頭

消除檔案UTF8格式的BOM頭

# -*- coding: utf-8 -*-
import HTMLParser
Parser = HTMLParser.HTMLParser() #解碼器
source = "&amp;&gt;"
source = Parser.unescape(source) #html轉移符解碼
print source

HTMLParser模組進行html轉移符解碼

import urllib
def urlEncode(str): #url編碼
    return urllib.urlencode({ "" : str })[1:]
word = "[email protected]#$%^&*()_+-= "
word = urlEncode(word)
print word

python2 urllib模組url編碼