簡體   English   中英

Scrapy:設置 cookies 以獲得響應(請求中沒有)

[英]Scrapy: set cookies for a response (no from request)

我需要以美元貨幣提取一些工資,但我正在從另一個國家/地區訪問該頁面,那么顯示的貨幣是當地(瑞爾)貨幣,沒有美元。 所以,我發送 cookies 請求新貨幣和新國家

在設置中我有:

COOKIES_ENABLED = False
COOKIES_DEBUG = True

在我使用的蜘蛛中:

class HtSpider(scrapy.Spider):
    name = 'sells'
    allow_domain = ['hattrick.org']

    def start_requests(self):
        urls = ['https://www.hattrick.org']
        for url in urls:
            player = 'goto.ashx?path=/Club/Players/Player.aspx?playerId=450940600'
            joint = urljoin(url, player)
            yield scrapy.Request(
                url=joint,
                cookies={'currency': 'USD', 'country': 'US'},
                # meta={'dont_merge_cookies': True},
                dont_filter=True,callback=self.price)
    def price(self,response):
       price_xpath = response.xpath('//* [@id="transferHistory"]/table//tr[1]/td[6]/text()').extract_first()
       print(price_xpath) // it is not in USD but in Riel :(
       open_in_browser(response) // to check if it is in Riel or in USD

然后,從 cookies 調試我得到:

DEBUG: Sending cookies to: <GET https://www.hattrick.org/en/Club/Players/Player.aspx?playerId=450940600> 
Cookie: currency=USD; country=US; currency=USD; country=US; ASP.NET_SessionId=xxxxx
2021-01-05 16:33:13 [scrapy.downloadermiddlewares.cookies] DEBUG: Received cookies from: <200 https://www.hattrick.org/en/Club/Players/Player.aspx?playerId=450940600>
Set-Cookie: InitialOrigin=Origin=direct|&DateSet=2021-01-05 10:33:13;

**Print price: 2 280 000 Riel**

如何獲取我發送的請求而不是來自網站的請求的 cookies? 簡而言之......如何獲得美元而不是瑞爾?

首先,您是否使用 Postman 進行了測試,以確保它確實適用於這個 cookie?

如果你有COOKIES_ENABLED = False那么 scrapy 不會將你的 cookies 發送到目標服務器。 由於您只向服務器發送一個請求,因此不會考慮來自服務器的 cookies。 所以設置COOKIES_ENABLED = True應該可以解決它。

但是,如果您需要向服務器發送多個請求,那么這可能不起作用,因為來自服務器的set_cookies標頭可能會覆蓋您的 cookie。

為了解決這個問題,我會設置COOKIES_ENABLED = False 然后像這樣發送請求:

yield scrapy.Request(
    url=joint,
    headers={
         'cookies': 'currency:USD;country:US'
    }
    dont_filter=True,callback=self.price)

我正在使用標題而不是 cookies 因為如果您在設置中禁用了 cookies ,則將考慮 cookies 字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM