0

大学で行っている研究のために、infoweb.newsbank.com のデータベースから記事を収集しようとしています。これまでのところ、これは私のコードです:

from bs4 import BeautifulSoup
import requests
import urllib
from requests import session
import http.cookiejar


mainLink  = "http://infoweb.newsbank.com.proxy.lib.uiowa.edu/iw-search/we/InfoWeb?p_product=AWNB&p_theme=aggregated5&p_action=doc&p_docid=14D12E120CD13C18&p_docnum=2&p_queryname=4"




def articleCrawler(mainUrl):
    response = urllib.request.urlopen(mainUrl)
    soup = BeautifulSoup(response)
    linkList = []
    for link in soup.find_all('a'):
        print(link)

articleCrawler(mainLink)

残念ながら、私はこの応答を返します:

<html>
<head>
<title>Cookie Required</title>
</head>
<body>
This is cookie.htm from the doc subdirectory.
<p>
<hr>
<p>

Licensing agreements for these databases require that access be extended
only to authorized users.  Once you have been validated by this system,
a "cookie" is sent to your browser as an ongoing indication of your authorization to
access these databases.  It will only need to be set once during login.
<p>
As you access databases, they may also use cookies.  Your ability to use those databases
may depend on whether or not you allow those cookies to be set.
<p>
To login again, click <a href="login">here</a>.
</p></p></p></hr></p></body>
</html>

<a href="login">here</a>

http.cookiejar を使用してみましたが、ライブラリに慣れていません。私は Python 3 を使用しています。Cookie を受け入れて記事にアクセスする方法を知っている人はいますか? ありがとうございました。

4

1 に答える 1

2

私は Python3 には詳しくありませんが、Python2 で Cookie を受け入れる標準的な方法はHTTPCookieProcessor、 をハンドラーの 1 つとしてに組み込むことOpenerDirectorです。

したがって、次のようなものです。

import cookielib, urllib, urllib2
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))

openerこれで、(おそらくユーザー名とパスワードを使用して) URL を開き、受信したすべての Cookie を統合された CookieJar に配置する準備が整いました。

params = urllib.urlencode({'username': 'someuser', 'password': 'somepass'})
opener.open(LOGIN_URL, params)

ログインが成功openerすると、サーバーが提供した認証トークンが Cookie 形式で保持されます。次に、最初に必要なリンクにアクセスするだけです。

f = opener.open(mainLink)

繰り返しますが、これが Python3 でどのように変換されるかはわかりませんが、cookielib.CookieJar少なくともhttp.cookiejar. 後者は、クライアントとして Cookie コンテンツを受信するためではなく、サーバーとして HTTP Cookie コンテンツを作成するためのものだと思います。

于 2014-04-11T22:27:47.093 に答える