2
votes

I'm setting the headers following way

headers = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'cache-control': 'no-cache',
...
}

And calling request like that:

yield scrapy.Request(url='https:/myurl.com/', callback=self.parse, 
headers=headers, cookies=cookies, meta={'proxy': 'http://localhost:8888'})

And it makes that scrapy capitalizes all these headers and it looks like that (I'm using Charles proxy for debugging):

Accept: 
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Cache-Control: no-cache

And this is not working correctly for my case.

If I'm using curl and set headers lowercase

accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
cache-control: no-cache

everything works like a charm.

Is there any way how I can disable this capitalizing behavior in Scrapy? Thanks for any help!

3
Are you sure that's the problem? HTTP headers should be case insensitive. - Chris
You can answer the above question by using curl with capitalized headers and checking whether it gives the same output. If it does, your problem isn't what you think it is. - holdenweb
Yea, I'm pretty sure about it. I guess the website I'm trying to parse is handling it some special way. - kspi33

3 Answers

1
votes

This can't be done out of the box with Scrapy.

Reason: it is managing headers in a case insensitive way by design (see: https://github.com/scrapy/scrapy/blob/master/scrapy/http/headers.py). Guess they do it to avoid trouble with duplicate headers.

So most probably you'll have to do a fork and roll your own implementation of header handling or do at least some monkey patching.

But I'm wondering whether that is really what you need. I know that some websites do request header fingerprinting to detect bots, but the capitalized headers generated by scrapy look much more non-bot than the all-lowercase headers you want to generate for your requests.

1
votes

This is my workaround. In your spider file you first create a class derived from Headers.

from copy import deepcopy
from scrapy.http import Headers
class Headers2(Headers):

    def __init__(self, seq=None, encoding='utf-8'):

        Headers.__init__(self, seq, encoding)

    def normkey(self, key):
        """Method to normalize dictionary key access"""
        return key.lower()

Then in your spider code

req = scrapy.Request(
                url=url,
                headers=header,
                callback=self.get_parcel_url
            )

h = Header2(copy.deepcopy(req.headers))
req.headers = h
0
votes

I've had blocking issues with two sites due to this. Here is my workaround that has worked both times:

headers={
    "":"accept-encoding: gzip, deflate, br",
    "":"accept-language: en-US,en;q=0.9,hi;q=0.8,pt;q=0.7",
}