2017-05-29 5 views
3

私は美しいスープとウェブページを数日間分析してきました。私は、私が書いたすべてのスクリプトに私の救い主であったコード行を使用してきました。コードの行です:urllib.request.urlopen(url)with Authentication

r = requests.get('some_url', auth=('my_username', 'my_password')). 

しかし...

私は(認証でURLを開く)と同じことをしたい:

(1) sauce = urllib.request.urlopen(url).read() (1) 
(2) soup = bs.BeautifulSoup(sauce,"html.parser") (2) 

私はにできませんよURLを開き、認証が必要なWebページを読んでください。 は、どのように私はこのような何かを達成します:

(3) sauce = urllib.request.urlopen(url, auth=(username, password)).read() (3) 
instead of (1) 

答えて

5

を公式ドキュメントからHOWTO Fetch Internet Resources Using The urllib Packageを見てください:

# create a password manager 
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() 

# Add the username and password. 
# If we knew the realm, we could use it instead of None. 
top_level_url = "http://example.com/foo/" 
password_mgr.add_password(None, top_level_url, username, password) 

handler = urllib.request.HTTPBasicAuthHandler(password_mgr) 

# create "opener" (OpenerDirector instance) 
opener = urllib.request.build_opener(handler) 

# use the opener to fetch a URL 
opener.open(a_url) 

# Install the opener. 
# Now all calls to urllib.request.urlopen use our opener. 
urllib.request.install_opener(opener) 
+0

問題の行(2)を参照してください。私は美しいスープを使ってソースを解析する必要があります。あなたのコードを使ってそれを達成するにはどうしたらいいですか? –

5

あなたはHTTP Basic Authenticationを使用している:

import urllib2, base64 

request = urllib2.Request(url) 
base64string = base64.b64encode('%s:%s' % (username, password)) 
request.add_header("Authorization", "Basic %s" % base64string) 
result = urllib2.urlopen(request) 

だからべきbase64はユーザー名とパスワードをエンコードし、Authorizationヘッダーとして送信します。

+0

import urllib2 ModuleNotFoundError: 'urllib2'というモジュールはありません –

+0

https://stackoverflow.com/questions/2792650/python3-error-import-error-no-module-name-urllib2を参照してください –