运行 urllib 审查请求时引发无效 URL 错误

我的代码如下:


import urllib.request as urllib


def read_text():

    quotes = open(r"C:\Users\hjayasinghe2\Desktop\Hasara Work\Learn\demofile.txt")

    contents_of_file = quotes.read()

    print(contents_of_file)

    quotes.close()

    check_pofanity(contents_of_file)


def check_pofanity(text_to_check):

    connection = urllib.urlopen("http://www.wdyl.com/profanity?q= " + text_to_check)

    output = connection.read()

    print(output)

    connection.close()


read_text()

我得到的错误是这样的:


Traceback (most recent call last):

  File "C:/Users/hjayasinghe2/Desktop/Hasara Work/Learn/check_profanity.py", line 16, in <module>

    read_text()

  File "C:/Users/hjayasinghe2/Desktop/Hasara Work/Learn/check_profanity.py", line 8, in read_text

    check_pofanity(contents_of_file)

  File "C:/Users/hjayasinghe2/Desktop/Hasara Work/Learn/check_profanity.py", line 11, in check_pofanity

    connection = urllib.urlopen("http://www.wdyl.com/profanity?q= " + text_to_check)

  File "C:\Users\hjayasinghe2\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 222, in urlopen

    return opener.open(url, data, timeout)

  File "C:\Users\hjayasinghe2\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 525, in open

    response = self._open(req, data)

  File "C:\Users\hjayasinghe2\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 543, in _open

    '_open', req)


炎炎设计
浏览 155回答 1
1回答

慕娘9325324

您需要对查询进行 URL 编码。尝试类似:import urllib, urllib.parseurl = "http://www.wdyl.com/profanity?q=" + urllib.parse.quote(text_to_check)connection = urllib.urlopen(url)见https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python