报错代码:

from urllib.robotparser import RobotFileParser
from urllib.request import urlopen

rp = RobotFileParser()
rp.parse(urlopen('https://www.jianshu.com/robots.txt').read().decode('utf-8').split('\n'))
print(rp.can_fetch('*', 'https://www.jianshu.com/p/e9eb86a6d120'))
print(rp.can_fetch('*', 'https://www.jianshu.com/u/080bb4eac1c9?utm_source=desktop&utm_medium=index-users'))

urlopen打开简书robots.txt时报错:HTTP Error 403: Forbidden

报错原因:用urllib.request.urlopen方式打开一个URL,服务器只会收到一个单纯的对于该页面访问的请求,但是服务器并不知道发送这个请求使用的浏览器,操作系统等信息,而缺失这些信息的访问往往都是非正常访问,会被一些网站禁止掉

 

解决办法:在headers中加入UserAgent

from urllib.robotparser import RobotFileParser
from urllib.request import urlopen, Request

rp = RobotFileParser()
headers = {
    'User-Agent': 'Mozilla/4.0(compatible; MSIE 5.5; Windows NT)'
}
req = Request('https://www.jianshu.com/robots.txt', headers=headers)
rp.parse(urlopen(req).read().decode('utf-8').split('\n'))
print(rp.can_fetch('*', 'https://www.jianshu.com/p/e9eb86a6d120'))
print(rp.can_fetch('*', 'https://www.jianshu.com/u/

urlopen打开简书robots.txt时报错:HTTP Error 403: Forbidden

 

 

 

爬取简书robots.txt时遇到的HTTP Error 403: Forbidden问题

 

 

 

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-31
  • 2021-12-14
  • 2022-02-03
  • 2021-12-12
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-13
  • 2021-06-18
  • 2021-09-27
  • 2021-08-26
相关资源
相似解决方案