登录站点并导航其他页面

2024-09-25 04:27:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python2的脚本,它可以登录到一个网页,然后移动到里面,访问指向同一个站点但不同页面上的两个文件。Python2让我用我的凭证打开这个站点,然后创建一个opener.open()来保持连接,以便导航到其他页面。在

以下是在Python2中工作的代码:

$Your admin login and password
LOGIN = "*******"
PASSWORD = "********"
ROOT = "https:*********"

#The client have to take care of the cookies.
jar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))

#POST login query on '/login_handler' (post data are: 'login' and 'password').
req = urllib2.Request(ROOT + "/login_handler",
                      urllib.urlencode({'login': LOGIN,
                                        'password': PASSWORD}))
opener.open(rep)

#Set the right accountcode

for accountcode, queues in QUEUES.items():
    req = urllib2.Request(ROOT + "/switch_to" + accountcode)
    opener.open(req)

我需要在python3中做同样的事情。我尝试过使用request module和urllib,但是尽管我可以建立第一个登录,但我不知道如何保持打开器来导航站点。我找到了开场白,但似乎我不知道怎么做,因为我还没有达到我的目标。在

我使用了这段python3代码来获得所需的结果,但不幸的是,我无法获得csv文件来打印它。 enter image description here


Tags: and文件代码站点loginrootpassword页面
2条回答

Question: I don't know how to keep the opener to navigate the site.

Python 3.6» Documentation urllib.request.build_opener

Use of Basic HTTP Authentication:

import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                      uri='https://mahler:8092/site-updates.py',
                      user='klem',
                      passwd='kadidd!ehopper')

opener = urllib.request.build_opener(auth_handler)

# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)
f = urllib.request.urlopen('http://www.example.com/login.html')
csv_content = f.read()

使用python3和session的python请求库。 http://docs.python-requests.org/en/master/user/advanced/#session-objects

一旦您登录,您的会话将被自动管理。你不需要创建自己的饼干罐。下面是示例代码。在

s = requests.Session()
auth={"login":LOGIN,"pass":PASS}
url=ROOT+/login_handler
r=s.post(url, data=auth)
print(r.status_code)
for accountcode, queues in QUEUES.items():
    req = s.get(ROOT + "/switch_to" + accountcode)
    print(req.text) #response text

相关问题 更多 >