Python 如何检测网址变化?
我正在写一个脚本,用来连接到WordPress网站,检测登录是否正确。我不想用“包含”这种方法,所以我尝试了这个:当你访问这个网址:http://www.example.com/blog/wp-admin/profile.php
时,如果输入的用户名和密码正确,你就能正常访问这个页面;如果不正确,网址会被重定向到这里:
http://www.example.com/blog/wp-login.php?redirect_to=http%3A%2F%2Fwww.example.com%2Fblog%2Fwp-admin%2Fprofile.php&reauth=1
所以我尝试了这个代码来验证HTTP响应(比如300,301等),但它总是返回200的响应……
import urllib, urllib2, os, sys, requests , re
from time import sleep
from threading import Thread
url='http://www.example.com/blog/wp-login.php'
headers = [
("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5")]
data = [
("log","user"),
("pwd","password"),
("testcookie",1),
("submit","Log In"),
("redirect_to","http://www.example.com/blog/wp-login.php"),
("rememberme","forever")]
#this is the first methode :
req = urllib2.Request(url, urllib.urlencode(dict(data)), dict(headers))
response = urllib2.urlopen(req)
the_page=response.read()
print the_page
#this is the seconde methode :
get3 = requests.get('http://www.example.com/blog/wp-admin/profile.php')
print get3.text
有没有什么办法可以检测网址从:http://www.example.com/blog/wp-admin/profile.php
变成:
http://www.example.com/blog/wp-login.php?redirect_to=http%3A%2F%2Fwww.example.com%2Fblog%2Fwp-admin%2Fprofile.php&reauth=1
或者有什么其他方法可以帮助我完成这个脚本,那就太好了,非常感谢! :)
1 个回答
3
有一个叫做Requests的第三方模块,它比Python自带的urllib简单很多。你可以在这里查看:http://docs.python-requests.org/en/latest/user/quickstart/#redirection-and-history
下面的内容来自这个链接。注意,最开始的url是用get请求的,但重定向后的url可以通过r.url获取(一个是http,重定向的是https)
>>> r = requests.get('http://github.com')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[<Response [301]>]
试试用你的url(当然不是'example.com')运行这段代码,看看会有什么结果