【问题标题】:Python article collection from a website that requires cookies来自需要 cookie 的网站的 Python 文章集合
【发布时间】:2014-04-11 21:15:59
【问题描述】:

我正在尝试从 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 并访问文章吗?谢谢。

【问题讨论】:

    标签: python cookies python-3.x web-scraping data-collection


    【解决方案1】:

    我不熟悉 Python3,但在 Python2 中,接受 cookie 的标准方法是将 HTTPCookieProcessor 合并为您的 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。我认为后者是作为服务器创建 HTTP cookie 内容而不是作为客户端接收 cookie 内容。

    【讨论】:

    • 好的,我会检查一下,稍后再评论。谢谢。
    猜你喜欢
    • 2011-07-03
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多