返回信息流之前不用scrapy框架时候,直接用requests.get(url, headers=headers)是可以正常抓取的,然后用scrapy抓取时候就被重定向了:
2014-07-25 00:31:27+0800 [demo] DEBUG: Redirecting (302) to <GET http://bbs.byr.
cn/?_escaped_fragment_=article%2FParttimeJob%2F> from <GET http://bbs.byr.cn/art
icle/ParttimeJob/>
我以为是headers没加,结果加上也还是被重定向了。[ema8]
求助各路大神,什么原因呢?
这是一条镜像帖。来源:北邮人论坛 / python / #1883同步于 2014/7/24
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
[问题]用scrapy爬byr板块被重定向
fastislow
2014/7/24镜像同步9 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
都会被重定向到http://bbs.byr.cn/#!/article/... 的,只不过requests比较机智,直接处理了重定向。
用history可以看到:
>>> import requests
>>> r = requests.get("http://bbs.byr.cn/article/Python/1883")
>>> r.history
[<Response [302]>]
>>>
requests不加headers的确也会重定向,然后重定向以后就抓不到我要的内容了啊。。它重定向到一个没有版块具体内容的地方了
【 在 Chon 的大作中提到: 】
: 都会被重定向到http://bbs.byr.cn/#!/article/... 的,只不过requests比较机智,直接处理了重定向。
: 用history可以看到:
: >>> import requests
: ...................
所以,你所谓加 header 你真知道该加什么 header 吗
【 在 fastislow 的大作中提到: 】
: requests不加headers的确也会重定向,然后重定向以后就抓不到我要的内容了啊。。它重定向到一个没有版块具体内容的地方了
加上 X-Requested-With:XMLHttpRequest
恩,在requests里面加了,而且抓回来是article里面内容,
http_headers = {"X-Requested-With":"XMLHttpRequest"}
r = requests.get("http://bbs.byr.cn/article/Python/1883", headers=http_headers)
用scrapy抓取加上headers还是被重定向。。,是不是我写的代码有问题?
spider里面自定义的DemoSpider.py:
import scrapy
class DemoSpider(scrapy.Spider):
name = "demo"
start_urls = ["http://bbs.byr.cn/article/ParttimeJob/"]
def parse(self, response):
filename = response.url.split("/")[-2]
with open(filename, 'ab') as f:
f.write(response.url)
return scrapy.Request(url="http://bbs.byr.cn/article/ParttimeJob/",headers ={'XRequested-With':'XMLHttpRequest'})
顺便问问,为什么requests加上headers才不会被重定向,而且为什么是这个固定的headers,是服务器会根据这个解析吗?
【 在 binux 的大作中提到: 】
: 所以,你所谓加 header 你真知道该加什么 header 吗
: 加上 X-Requested-With:XMLHttpRequest
google XMLHttpRequest
【 在 fastislow 的大作中提到: 】
: 恩,在requests里面加了,而且抓回来是article里面内容,
: [code=py]
: http_headers = {"X-Requested-With":"XMLHttpRequest"}
: ...................