簡體   English   中英

為什么我的網址訪問失敗?

[英]Why does my url access fail?

好的,所以我有一個網站,我正在制作一個python腳本,以將數據作為GET請求發送到php腳本,從而將數據插入到網站中,但是每當我放置不包含字母或數字字符ex(@ [ ]; :)我收到一個urllib錯誤,說我的URL中沒有主機:

        return urllib.urlopen("http://this-is-an-example.com/thisisadirectory/file.php?f=Hello&v="+cgi.escape("This is@A#!T33ST::::;'[]{}"))
      File "Python25\lib\urllib.py", line 82, in urlopen
        return opener.open(url)
      File "Python25\lib\urllib.py", line 190, in open
        return getattr(self, name)(url)
      File "Python25\lib\urllib.py", line 301, in open_http
        if not host: raise IOError, ('http error', 'no host given')
    IOError: [Errno http error] no host given

我還嘗試制作自己的轉義函數以轉義所有特殊字符(或至少幾個)

    full_escape_chars = {" ": "%20",
                    "<": "%3C",
                    ">": "%3E",
                    "#": "%23",
                    "\%": "%25",
                    "{": "%7B",
                    "}": "%7D",
                    "|": "%7C",
                    "\\": "%5C",
                    "^": "%5E",
                    "~": "%7E",
                    "[": "%5B",
                    "]": "%5D",
                    "`": "%60",
                    ";": "%3B",
                    "/": "%2F",
                    "?": "%3F",
                    ":": "%3A",
                    "@": "%40",
                    "=": "%3D",
                    "&": "%26",
                    "$": "%24"}
    def full_escape(s):
        global full_escape_chars
        for key in full_escape_chars.keys():
            s = s.replace(key, full_escape_chars[key])
        return s

但是,仍然沒有。 請提出如何解決此問題的建議! 提前致謝。

一個問題可能是cgi.escape並沒有按照您的想象做。 urllib.quote_plus

>>> import cgi
>>> import urllib
>>> s = "This is@A#!T33ST::::;'[]{}"
>>> cgi.escape(s)
"This is@A#!T33ST::::;'[]{}"
>>> urllib.quote_plus(s)
'This+is%40A%23%21T33ST%3A%3A%3A%3A%3B%27%5B%5D%7B%7D'

cgi.escape(s[, quote])

 Convert the characters '&', '<' and '>' in string s to HTML-safe sequences. Use this if you need to display text that might containsuch characters in HTML. 

一般而言,這表現得更加合理:

>>> urllib.urlopen("http://this-is-an-example.com/thisisadirectory/file.php?f=Hello&v="+urllib.quote_plus("Thi
s is@A#!T33ST::::;'[]{}"))
<addinfourl at 24629656 whose fp = <socket._fileobject object at 0x16ebc30>>
>>> _.read()
'<?xml version="1.0" encoding="iso-8859-1"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\n
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html xmlns="http://www.w3.org/1999/xhtml
" xml:lang="en" lang="en">\n <head>\n  <title>404 - Not Found</title>\n </head>\n <body>\n  <h1>404 - Not Foun
d</h1>\n </body>\n</html>\n'
>>> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM