Python Detect Url更改?

时间:2014-08-09 13:44:13

标签: python wordpress http url

我正在创建一个连接到wordpress的脚本并检测登录是否不正确,我不喜欢"如果包含"方法所以我试着用这个: 当您在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 个答案:

答案 0 :(得分: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]>]

使用您的网址尝试此代码(显然不是&#39; example.com&#39;)并查看其产生的内容