2015-11-12 2 views
0

У меня есть следующий код:Представляющие значения объекта __str__

import urllib 

class Get: 

    def sendData(self): 
     self.data = urllib.urlencode({"contains":"silabeador"}) 
     self.u = urllib.urlopen('http://tip.iatext.ulpgc.es/silabas/default.aspx', data) 

request=Get() 
print (request.sendData) 

Мой выход или возвращаемое значение данных, передаваемых в URL является следующее:

<bound method Get.sendData of <__main__.Get instance at 0x7f6089f5e050>> 

Как я могу получить значение объект Get, а не их представление?

Кстати, я новичок в python, заинтересован в отправке на какой-либо сайт нескольких значений и что этот сайт получает эти значения в texbox и выполняет поиск и извлечение этих значений поиска. Я говорю это, потому что библиотека запросов действительно отличная альтернатива?

С наилучшими пожеланиями

EDIT

Я организовали мой маленький код этого лучшего способа:

import urllib 

class Get:    
    def __init__(self): 
     data = urllib.urlencode({"contains":"silabeador"}) 
     u = urllib.urlopen('http://localhost:8000/login/', data) 
     print(u.read()) 
request=Get() 
print request 

И когда я пытаюсь получить значение моей маленькой страницы (на мой localhost machine) Я получаю их, но в конце я также вижу значение объекта, < main. Получите экземпляр на 0x7f052c4e00e 0> значение в конце ...

➜ ~ python2 pageGET.py   

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
    <meta name="robots" content="NONE,NOARCHIVE"> 
    <title>403 Forbidden</title> 
    <style type="text/css"> 
    html * { padding:0; margin:0; } 
    body * { padding:10px 20px; } 
    body * * { padding:0; } 
    body { font:small sans-serif; background:#eee; } 
    body>div { border-bottom:1px solid #ddd; } 
    h1 { font-weight:normal; margin-bottom:.4em; } 
    h1 span { font-size:60%; color:#666; font-weight:normal; } 
    #info { background:#f6f6f6; } 
    #info ul { margin: 0.5em 4em; } 
    #info p, #summary p { padding-top:10px; } 
    #summary { background: #ffc; } 
    #explanation { background:#eee; border-bottom: 0px none; } 
    </style> 
</head> 
<body> 
<div id="summary"> 
    <h1>Prohibido <span>(403)</span></h1> 
    <p>CSRF verificacion fallida. Solicitud abortada</p> 


    <p>Estás viendo este mensaje porqué esta web requiere una cookie CSRF cuando se envían formularios. Esta cookie se necesita por razones de seguridad, para asegurar que tu navegador no ha sido comprometido por terceras partes.</p> 
    <p>Si has inhabilitado las cookies en tu navegador, por favor habilítalas nuevamente al menos para este sitio, o para solicitudes del mismo origen.</p> 

</div> 

<div id="info"> 
    <h2>Help</h2> 

    <p>Reason given for failure:</p> 
    <pre> 
    CSRF cookie not set. 
    </pre> 


    <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when 
    <a 
    href="https://docs.djangoproject.com/en/1.8/ref/csrf/">Django's 
    CSRF mechanism</a> has not been used correctly. For POST forms, you need to 
    ensure:</p> 

    <ul> 
    <li>Your browser is accepting cookies.</li> 

    <li>The view function passes a <code>request</code> to the template's <a 
    href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a> 
    method.</li> 

    <li>In the template, there is a <code>{% csrf_token 
    %}</code> template tag inside each POST form that 
    targets an internal URL.</li> 

    <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use 
    <code>csrf_protect</code> on any views that use the <code>csrf_token</code> 
    template tag, as well as those that accept the POST data.</li> 

    </ul> 

    <p>You're seeing the help section of this page because you have <code>DEBUG = 
    True</code> in your Django settings file. Change that to <code>False</code>, 
    and only the initial error message will be displayed. </p> 

    <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p> 
</div> 

</body> 
</html> 

**<__main__.Get instance at 0x7f052c4e00e0>** 
+1

Что вы намерены выход быть? В вашем примере вы не вызываете метод; для этого вам понадобится 'request.sendData()'. Evne, если вы это сделаете, возвращаемое значение ничего вам не покажет, потому что вы ничего не возвращаете из своего метода. – BrenBarn

+1

'obj.function_name' = ссылка на функцию; 'obj.function_name()' = вызов функции и получить ее возвращаемое значение. Вы должны иметь круглые скобки. –

+0

@BrenBarn и Two-Bit Alchemist мои извинения за эту ошибку новичка. Большое спасибо за наблюдение – bgarcial

ответ

3

с помощью

print (request.sendData) 

вы justing печати определения метода для sendData().

Чтобы распечатать данные, вам просто нужно использовать print (request.data) , так как вы определили его в своем методе класса.

EDIT:

Давайте посмотрим на то, что вы делаете в вашем втором __init__() метода.

def __init__(self): 
    1- data = urllib.urlencode({"contains":"silabeador"}) 
    2- u = urllib.urlopen('http://localhost:8000/login/', data) 
    3- print(u.read()) 

1- Вы кодирующие данные

2- Вы открытия URL

3- Вы чтение из URL и печать. Результатом является страница html.

Тогда рядом, на этой линии

request=Get() 

Вы создаете экземпляр Получить и присваиваем его request, Далее, вы печатаете request, который является ссылкой на объект.

Итак, вы хотите распечатать только содержимое страниц? Вы можете:

1- Удалить ваш метод в print request

2- Изменение:

def __init__(self): 
     data = urllib.urlencode({"contains":"silabeador"}) 
     u = urllib.urlopen('http://localhost:8000/login/', data) 
     self.data = u.read() #assign the page content to an attribute 

request = Get() 
print request.data #print the data attribute. 
Смежные вопросы