一、利用webbrowser.open()打開一個網站:
>>> import webbrowser >>> webbrowser.open('http://i.firefoxchina.cn/?from=worldindex') True
實例:使用腳本打開一個網頁。
所有Python程序的第一行都應以#!python開頭,它告訴計算機想讓Python來執行這個程序。(我沒帶這行試了試,也可以,可能這是一種規范吧)
1.從sys.argv讀取命令行參數:打開一個新的文件編輯器窗口,輸入下面的代碼,將其保存為map.py。
2.讀取剪貼板內容:
3.調用webbrowser.open()函數打開外部瀏覽:
#! python3 import webbrowser, sys, pyperclip if len(sys.argv) > 1: mapAddress = ''.join(sys.argv[1:]) else: mapAddress = pyperclip.paste() webbrowser.open('http://map.baidu.com/?newmap=1&ie=utf-8&s=s%26wd%3D' + mapAddress
注:不清楚sys.argv用法的,請參考這里;不清楚.join()用法的,請參考這里。sys.argv是字符串的列表,所以將它傳遞給join()方法返回一個字符串。
好了,現在選中'天安門廣場'這幾個字并復制,然后到桌面雙擊你的程序。當然你也可以在命令行找到你的程序,然后輸入地點。
二、用requests模塊從Web下載文件:requests模塊不是Python自帶的,通過命令行運行pip install request安裝。沒翻墻是很難安裝成功的,手動安裝可以參考這里。
>>> import requests >>> res = requests.get('http://i.firefoxchina.cn/?from=worldindex') #向get中傳入一個網址 >>> type(res) #響應對象 <class 'requests.models.Response'> >>> print(res.status_code) #響應碼 200 >>> res.text #返回的文本
requests中查看網上下載的文件內容的方法還有很多,如果以后的博客用的到,會做說明,在此不再一一介紹。在下載文件的過程中,用raise_for_status()方法可以確保下載確實成功,然后再讓程序繼續做其他事情。
import requests res = requests.get('http://i.firefoxchina.cn/?from=worldindex') try: res.raise_for_status() except Exception as exc: print('There was a problem: %s' % (exc))
三、將下載的文件保存到本地:
>>> import requests >>> res = requests.get('http://tech.firefox.sina.com/17/0820/10/6DKQALVRW5JHGE1I.html##0-tsina-1-13074-397232819ff9a47a7b7e80a40613cfe1') >>> res.raise_for_status() >>> file = open('1.txt', 'wb') #以寫二進制模式打開文件,目的是保存文本中的“Unicode編碼” >>> for word in res.iter_content(100000): #<span class="fontstyle0"><span class="fontstyle0">iter_content()</span><span class="fontstyle1">方法在循環的每次迭代中返回一段</span><span class="fontstyle0">bytes</span><span class="fontstyle1">數據</span><span class="fontstyle1">類型的內容,你需要指定其包含的字節數</span></span> file.write(word) 16997 >>> file.close()
新聞熱點
疑難解答