hi I am trying to access the page through mechanize get method.The page takes cookie of the previous page post request to give response.
Can anyone tell me how to pass the cookie in the header of get method of Mechanize?
I am trying the approach mentioned below but not hitting the result page not getting data of result page..
def get_body_2
{
"ctl00$Content$ddSpecialization" => "Appellate Practice"
}
end
def post_request
url = 'https://portal.ncbar.gov/verification/search.aspx'
body = get_body_2
page = #agent.post(url,body)
#cookie_val = #agent.cookies[0]
end
def mechanize_call
url = 'https://portal.ncbar.gov/Verification/results.aspx'
byebug
page = #agent.get(url,{"Cookie" => #cookie_val})
end
Related
In testing Django, the view is returning 200 code but not sending any error message related.
def ajax_view(request):
msg = ''
if request.is_ajax():
username = request.POST['username']
user = User.objects.get(username=username)
msg = 'user exists'
return HttpResponse(msg)
In tests.py
response = self.client.post(reverse('ajax_view'), data={'username': 'hello'})
self.assertEqual(200, response.status_code)
self.assertContains(response, 'exist')
It seems it is not going through the request.is_ajax().. How can I mock the ajax call in Django testing?
The docs on the test client mention this; you need to pass the HTTP_X_REQUESTED_WITH header, which you can do as a keyword argument.
Also, if you pass content_type as 'application/json', Django will automatically serialize to JSON. So:
response = self.client.post(
reverse('ajax_view'),
data={'username': 'hello'},
content_type='application/json',
HTTP_X_REQUESTED_WITH='XMLHttpRequest'
)
Not entirely sure this will resolve the entire issue but your method may be expecting the data in a json format:
json_data = json.dumps({'username': 'hello'})
response = self.client.post(reverse('ajax_view'), data=json_data)
I am trying to log into a site programmatically using the Mechanize Ruby library and then access the content available as a signed in user.
# intantiating a Mechanize instance
#agent = Mechanize.new
# username and password for site log in
username = "username"
password = "password"
#load site site
page = #agent.get("https://someDomain.com/")
# get the login form
form = #agent.page.forms.first
#fill the form with credentials
form.field_with(:name => "username").value = username
form.field_with(:name => "password").value = password
form.method = "POST"
#submit the login form
page = form.submit
Once the form submitted the Mechanize object assigned to page has a url property that looks like this:
{url
#<URI::HTTPS https://someDomain.com/?username=username&password=password#>
}
I think the way I'm passing my username and password to the url through the use of Mechanize is wrong because it looks like the website doesn't do that when I go and sign in manually.
Question
Does the local variable page contain the response page that is shown once the user is logged in?
I now want to access certain urls that only signed in user have access to-- what do I need to do?
I am trying to test and AJAX view in my Django Project. When submit the post from JQuery the data is correctly accessible in the Django View but when I try to make queries for the Django test client it is emplty.
Here is the code I use:
The view
def add_item(request):
if request.is_ajax() and request.method == 'POST':
post_data = request.POST
print post_data ## <----- THIS IS EMPTY
name = post_data.get('name')
# Render the succes response
json_data = json.dumps({"success":1})
return HttpResponse(json_data, content_type="application/json")
else:
raise Http404
And the test
class TestAddItem(TestCase):
def test_some_test(self):
data = {
'description':"description",
}
response = self.client.post('theurl', data, content_type='application/json')
Any Idea what I might be doing wrong?
I tried also without content type and also using plain url like thurl/?name=name without succes.
Any help will be appreciated.
Olivier
After trying different combinations of parameter formating, content types, etc..
I found one solution that works :
response = self.client.post(reverse('theurl'), data,
**{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'})
And I get the following dictionary on the POST parameters of the request:
<QueryDict: {u'name': [u'name']}>
Edit I love testing :)
I have this code, and I login successfully:
require 'mechanize'
require 'logger'
agent = Mechanize.new{|a| a.log = Logger.new(STDERR) }
agent.read_timeout = 60
def add_cookie(agent, uri, cookie)
uri = URI.parse(uri)
Mechanize::Cookie.parse(uri, cookie) do |cookie|
agent.cookie_jar.add(uri, cookie)
end
end
page = agent.get "http://www.webpage.com"
form = page.forms.first
form.correo_ingresar = "user"
form.password = "password"
page = agent.submit form
myarray = page.body.scan(/SetCookie\(\"(.+)\", \"(.+)\"\)/)
After I login I do not get redirected, so I looked at the webpage and Java is the one redirecting me, but if I use page = agent.get("http://webpage.com") all session cookies are deleted. And I have to login again , and it is a cycle because I don't get past that. I already tried several recommendations like ignore_discard
It looks like you have the right code to add the cookie but forgot to call it.
At the end try:
myarray.each{|line| add_cookie agent, 'http://www.sistemasaplicados.com.mx', "#{line[0]}=#{line[1]}"}
Mechanize automatically receives, stores, and sends cookies when using the same instance to get new pages.
Are you certain that the site is actually sending cookies?
Have you confirmed that Mechanize is really not sending the cookies? (Have you inspected the request headers it sends?)
You said "Java is [...] redirecting me"; did you really mean JavaScript?
I have a Grails controller action that is used for Ajax purposes, though you can still navigate and view the page in the browser.
class QuoteController {
def quoteService
/**
* This page uses the ajaxRandom function defined below to display random quotes.
*/
def random = {
def randomQuote = quoteService.getRandomQuote()
[quote:randomQuote]
}
/**
* I do not want this to be a valid page, but maintain its use as a simple Ajax method.
*/
def ajaxRandom = {
def randomQuote = quoteService.getRandomQuote()
response.outputStream << "<q>${randomQuote.content}</q><p>${randomQuote.author}</p>"
}
}
Is there a way to redirect if someone visits the URL via browser while maintaining the method's Ajax functionality from within a page?
def ajaxRandom = {
if(!request.xhr) { // this calls the dynamic method request.isXhr()
redirect action: 'random'
} else {
def randomQuote = quoteService.getRandomQuote()
response.outputStream << "<q>${randomQuote.content}</q><p>${randomQuote.author}</p>"
}
}
This works because most of the Ajax JS Libraries add the X-Requested-With header to the request. Grails add this isXhr() method dynamically to the HttpServletRequest class.
// test whether the current request is an XHR request
HttpServletRequest.metaClass.isXhr = {->
'XMLHttpRequest' == delegate.getHeader('X-Requested-With')
}
A simple way is to append a param to the url when calling it via ajax e.g. ?ajax=true
Then check for it and redirect if it's not there (such as when a use hits it with their browser).
If that is too easy to work around, inspect the request to see what is different between a browser request and an ajax request.
cheers
Lee
If you AJAX requests are always POSTS then you could check the method and assume a POST is an AJAX call because it's pretty hard for the average user to create a POST accidentally, where as they can always GET any URL (if they know of it)
Hope this helps.