为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

炎炎设计 2022-06-14 16:28:14
我的代码如下:import urllib.request as urllibdef 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)
查看完整描述

1 回答

?
慕娘9325324

TA贡献1783条经验 获得超4个赞

您需要对查询进行 URL 编码。尝试类似:


import urllib, urllib.parse

url = "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


查看完整回答
反对 回复 2022-06-14
  • 1 回答
  • 0 关注
  • 151 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信