我想用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': '',
'passwd': ''
}
# 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()