[已解决] urllib.error.HTTPError: HTTP Error 400: Invalid header received from client的解决方案

来自Udacity的冒犯语检测的实验

问题代码以及报错信息

右边这段代码用python2.7可以运行,python3就会报错
如何解决? 如下:
原代码:
def check_profanity(text_to_check):
    connection = ur.urlopen(
        "http://www.wdylike.appspot.com/?q=" + text_to_check)
    output = connection.read()
    print(output)
    connection.close()

修改后:
def check_profanity(text_to_check):
	
	text_to_check = urllib.parse.quote(text_to_check) #增加此段
	
    connection = ur.urlopen(
        "http://www.wdylike.appspot.com/?q=" + text_to_check)
    output = connection.read()
    print(output)
    connection.close()
只是解析text_to_check

修改后再次运行:

问题得到解决

问题得到解决

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当你使用 urllib 库进行网络请求时,出现 HTTP Error 403: Forbidden 错误,这意味着服务器拒绝了你的请求。这通常是因为你的请求被防火墙或网站服务器拦截。 有一些方法可以解决这个问题: 1. 修改 User-Agent 有些网站会根据 User-Agent 来判断请求的来源,如果 User-Agent 不合法,就会拒绝请求。因此,你可以通过修改 User-Agent 来模拟浏览器请求。例如: ```python import urllib.request url = 'http://www.example.com/' headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'} req = urllib.request.Request(url, headers=headers) response = urllib.request.urlopen(req) html = response.read() ``` 2. 使用代理IP 如果你的 IP 被网站服务器封禁,可以使用代理 IP 来绕过限制。例如: ```python import urllib.request url = 'http://www.example.com/' proxy = urllib.request.ProxyHandler({'http': 'http://127.0.0.1:8888'}) opener = urllib.request.build_opener(proxy) urllib.request.install_opener(opener) response = urllib.request.urlopen(url) html = response.read() ``` 其中,`http://127.0.0.1:8888` 是代理服务器的地址。你可以在网上找到一些免费的代理服务器,在代码中修改为对应的地址即可。 3. 等待一段时间再请求 有些网站会对频繁请求进行限制,你可以等待一段时间再进行请求,或者减少请求频率。如果你是在爬取大量数据,建议使用异步爬虫库,如 asyncio、aiohttp 等,可以提高效率,并减少请求频率。 以上是一些常见的方法,但不保证一定可以解决问题。在实际操作中,还需要根据具体情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值