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

4
我是一名有用的助手,可以为您翻译文本。
我正在尝试使用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()">

它不能工作,打印resp.read()仍然返回“<td> <p>此数据的访问仅限订阅。<a href="freetrialapplication/">点击此处</a>免费试用。</p> </td>”。 - lsheng
@André 我注意到登录页面需要3个项目,我已经拥有了它们,但我不确定应该如何将它们放入login_info中? - lsheng
我已经编辑过了,但不确定这是否是您要求的。在打印resp.read()结果中,我没有找到<form>。 - lsheng
3个回答

1

使用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或甚至urllib中的一行代码就可以完成相同的操作。 - user2629998
我现在没有Scrapy,我必须要求IT为我安装它,因为Python在服务器上。 - lsheng

1

这段代码应该可以工作,使用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)

谢谢,但在resp变量中我仍然有"><p>访问此数据仅限订阅。<a href="freetrialapplication/">点击这里</a>免费试用。</p>"..... 我确定登录名是正确的。 - lsheng

0

尝试在头部中使用另一个用户代理。看起来该网站有某种类型的爬虫检测,您没有提供要检查的URL。 有些网站进行JavaScript测试以检查请求是否自动化,在这种情况下,请选择playwright或selenium。


这并没有回答问题。一旦您拥有足够的声望,您将能够评论任何帖子;相反,提供不需要询问者澄清的答案。- 来自审核 - Benjamin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接