繁体   English   中英

如何使用 Python 从需要登录信息的网站下载文件?

[英]How to download file from website that requires login information using Python?

我正在尝试使用 Python 从网站下载一些数据。 如果您只是复制并粘贴 url,除非您填写登录信息,否则它不会显示任何内容。 我有登录名和密码,但是我应该如何将它们包含在 Python 中?

我目前的代码是:

import urllib, urllib2, cookielib

username = my_user_name
password = my_pwd

link = 'www.google.com' # just for instance
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})

opener.open(link, login_data)
resp = opener.open(link,login_data)
print resp.read()

没有错误弹出,但是 resp.read() 是一堆 CSS,它只有“你必须先登录才能在这里阅读新闻”这样的消息。

那么如何找回登录后的页面呢?

刚刚注意到该网站需要 3 个条目:

Company: 

Username: 

Password:

我拥有所有这些,但是如何将所有三个都放在登录变量中?

如果我在没有登录的情况下运行它,它会返回:

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

opener.open(dd)
resp = opener.open(dd)

print resp.read()

这是打印输出:

<DIV id=header>
<DIV id=strapline><!-- login_display -->
<P><FONT color=#000000>All third party users of this website and/or data produced by the Baltic do so at their own risk. The Baltic owes no duty of care or any other obligation to any party other than the contractual obligations which it owes to its direct contractual partners. </FONT></P><IMG src="images/top-strap.gif"> <!-- template [strapline]--></DIV><!-- end strapline -->
<DIV id=memberNav>
<FORM class=members id=form1 name=form1 action=client_login/client_authorise.asp?action=login method=post onsubmits="return check()">

Usign scrapy 用于抓取该数据, Scrapy

然后你可以这样做

class LoginSpider(Spider):
    name = 'example.com'
    start_urls = ['http://www.example.com/users/login.php']

    def parse(self, response):
        return [FormRequest.from_response(response,
                    formdata={'username': 'john', 'password': 'secret'},
                    callback=self.after_login)]

    def after_login(self, response):
        # check login succeed before going on
        if "authentication failed" in response.body:
            self.log("Login failed", level=log.ERROR)
            return

这段代码应该可以工作,使用Python-Requests - 只需将...替换为实际域,当然还有登录数据。

from requests import Session

s = Session() # this session will hold the cookies

# here we first login and get our session cookie
s.post("http://.../client_login/client_authorise.asp?action=login", {"companyName":"some_company", "password":"some_password", "username":"some_user", "status":""})

# now we're logged in and can request any page
resp = s.get("http://.../").text

print(resp)

尝试在标题中使用另一个用户代理。 看起来该站点具有某种类型的刮板检测,您没有提供用于检查的 URL。 一些网站进行 javascript 测试以检查请求是否看起来是自动化的,在这种情况下,请使用 playwright 或 selenium。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM