5

此 shell 命令成功

$ curl -A "Mozilla/5.0 (X11; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0 (compatible;)" http://fifa-infinity.com/robots.txt

并打印 robots.txt。省略 user-agent 选项会导致服务器出现 403 错误。检查 robots.txt 文件显示http://www.fifa-infinity.com/board下的内容允许抓取。但是,以下失败(python 代码):

import logging
import mechanize
from mechanize import Browser

ua = 'Mozilla/5.0 (X11; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0 (compatible;)'
br = Browser()
br.addheaders = [('User-Agent', ua)]
br.set_debug_http(True)
br.set_debug_responses(True)
logging.getLogger('mechanize').setLevel(logging.DEBUG)
br.open('http://www.fifa-infinity.com/robots.txt')

我的控制台上的输出是:

No handlers could be found for logger "mechanize.cookies"
send: 'GET /robots.txt HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.fifa-infinity.com\r\nConnection: close\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0 (compatible;)\r\n\r\n'
reply: 'HTTP/1.1 403 Bad Behavior\r\n'
header: Date: Wed, 13 Feb 2013 15:37:16 GMT
header: Server: Apache
header: X-Powered-By: PHP/5.2.17
header: Vary: User-Agent,Accept-Encoding
header: Connection: close
header: Transfer-Encoding: chunked
header: Content-Type: text/html
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/moshev/Projects/forumscrawler/lib/python2.7/site-packages/mechanize/_mechanize.py", line 203, in open
    return self._mech_open(url, data, timeout=timeout)
  File "/home/moshev/Projects/forumscrawler/lib/python2.7/site-packages/mechanize/_mechanize.py", line 255, in _mech_open
    raise response
mechanize._response.httperror_seek_wrapper: HTTP Error 403: Bad Behavior

奇怪的是,在不设置用户代理的情况下使用 curl 会导致“403:禁止”而不是“403:不良行为”。

我是不是做错了什么,或者这是 mechanize/urllib2 中的错误?我看不出简单地获取 robots.txt 会是“不良行为”吗?

4

1 回答 1

9

经实验验证,您需要添加一个Accept标头来指定可接受的内容类型(任何类型都可以,只要“Accept”标头存在)。例如,更改后将起作用:

br.addheaders = [('User-Agent', ua)]

至:

br.addheaders = [('User-Agent', ua), ('Accept', '*/*')]
于 2013-02-13T16:51:48.143 回答