2017-06-07 75 views
0

我現在正在使用它的api在新浪微博爬蟲上開玩笑。 爲了使用api,我必須訪問oauth2授權頁面才能從url中檢索代碼。如何解析響應url而不實際打開python中的網頁?

這正是我該怎麼做:

  1. 使用我APP_KEY和app_secret(均爲已知)

  2. 得到的oauth2網頁

  3. 複製的URL粘貼從響應代碼手動URL。

這是我的代碼:

#call official SDK 
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL) 

#get url of callback page of authorization 
url = client.get_authorize_url() 
print url 

#open webpage in browser 
webbrowser.open_new(url) 

#after the webpage responding, parse the code part in the url manually 
print 'parse the string after 'code=' in url:' 
code = raw_input() 

我的問題是究竟如何擺脫手動解析部分的?

參考: http://blog.csdn.net/liuxuejiang158blog/article/details/30042493

+0

看看['requests'](http://docs.python-requests.org/en/master/)模塊 –

回答

0

要獲得使用請求頁面的內容,你可以這樣做

import requests 

url = "http://example.com" 

r = requests.get(url) 

print r.text 

你可以看到圖書館here請求的細節。你可以使用pip將它安裝到你的virtualenv/python dist中。

對於書寫履帶式,您還可以使用scrapy

最後,我不明白一件事,如果你有一個正式的客戶端,那麼爲什麼你需要解析一個URL的內容來獲取數據。客戶不會使用一些很好用的功能爲您提供數據嗎?

+0

好的!從你的主要問題不明白。你有沒有嘗試過使用[selenium](http://www.seleniumhq.org/)他們也有[python binding](https://selenium-python.readthedocs.io/)? – SRC

+0

我會盡力回覆你,再次感謝你! – shin

+0

不客氣!希望它能幫助你。如果你不限於python,那麼你也可以查看[PhantomJS](http://phantomjs.org/)。 – SRC

相關問題