HTTP 错误 400 错误请求 python

HTTP Error 400 bad request python

from urllib.request import *
import urllib

def read_text():
    text = open("/home/pizzapablo666/Desktop/Test")
    contents_of_file = text.read()
    print(contents_of_file)
    text.close()
    check_profanity(contents_of_file)


def check_profanity(text_to_check):
    text_to_check = urllib.parse.quote_plus(text_to_check)
    connection = urlopen(
        "http://www.wdylike.appspot.com/?q=" + text_to_check)
    output = connection.read()
    print(output)
    connection.close()

read_text()

这是更新版本
HTTP 400 错误错误请求,是什么原因?我该如何解决这个错误?

我认为这是因为您在将字符串附加到 url 之前没有对其进行编码。

例如,在 python3 中,您应该对 'text_to_check' 执行以下操作,然后再将其附加到 url:

text_to_check = urllib.parse.quote_plus(text_to_check)

Python2 会是这样的(urllib 在 python3 中被分解成更小的组件):

text_to_check = urllib.quote_plus(text_to_check)

这意味着,当将带空格的字符串附加到您的 url 时,它将显示为 "Am+I+cursing%3F" 而不是 "Am I cursing?"。

完整 check_profanity() 示例:

def check_profanity(text_to_check):
    text_to_check = urllib.parse.quote_plus(text_to_check)
    connection = urlopen(
        "http://www.wdylike.appspot.com/?q=" + text_to_check)
    output = connection.read()
    print(output)
    connection.close()