gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 21:50:03 24 4
gpt4 key购买 nike

我正在尝试使用 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()">

最佳答案

此代码应该有效,使用 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)

关于python - 如何使用 Python 从需要登录信息的网站下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22802666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com