0

我想用python访问网页并打印源代码,其中大多数都需要首先登录。我之前遇到过类似的问题,我已经用下面的代码解决了,因为它们是网页上的修复字段,我可以找到它们。最近需要访问另外一个页面,但是这次弹出登录窗口,无法用同样的方法解决问题。

我曾尝试使用 Selenium 模块,但它需要打开浏览器并做到这一点,只是想知道是否有与 cookielib 类似的方法让 python 在后台运行代码而不注意到浏览器已打开?非常感谢!

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()

在此处输入图像描述

4

1 回答 1

2

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

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

所以你可能想看看这个协议并基于它创建一个请求,而不是尝试将你的登录名放在弹出窗口中。

于 2015-12-19T13:56:20.047 回答