弹出窗口的Python登录页面

2024-03-29 10:42:29 发布

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

我想用python访问网页并打印源代码,大多数都需要先登录。我以前也有类似的问题,我已经用下面的代码解决了,因为它们是网页上的修复字段,我可以找到它们。最近,我需要访问another page,但这一次,有一个弹出的登录窗口,我不能使用相同的方法来解决这个问题。在

我曾经尝试过使用Selenium模块,但是它需要打开浏览器并完成这个任务,只是想知道是否有类似于cookielib的方法在后台运行代码而不注意浏览器已经打开了?非常感谢!在

import cookielib
import urllib
import urllib2


# Store the cookies and create an opener that will hold them
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

# Add our headers
opener.addheaders = [('User-agent', 'RedditTesting')]

# Install our opener (note that this changes the global opener to the one
# we just made, but you can also just call opener.open() if you want)
urllib2.install_opener(opener)

# The action/ target from the form
authentication_url = 'https://ssl.reddit.com/post/login'

# Input parameters we are going to send
payload = {
  'op': 'login-main',
  'user': '<username>',
  'passwd': '<password>'
  }

# Use urllib to encode the payload
data = urllib.urlencode(payload)

# Build our Request object (supplying 'data' makes it a POST)
req = urllib2.Request(authentication_url, data)

# Make the request and read the response
resp = urllib2.urlopen(req)
contents = resp.read()

enter image description here


Tags: andtheto方法代码import网页data
1条回答
网友
1楼 · 发布于 2024-03-29 10:42:29

您可以将selenium与PhantomJS一起使用,以获得无头浏览器。还有一个使用WebKit解释Javascript的Ghost.py。这两个项目有助于与webapps的js内容进行交互。在

但是我注意到弹出窗口是由于HTTP身份验证协议引起的,这里它似乎是https://en.wikipedia.org/wiki/NT_LAN_Manager

因此,您可能需要查看此协议并基于该协议创建一个请求,而不是尝试在弹出窗口中输入您的登录名。在

相关问题 更多 >