【问题标题】:Scrapy with selenium and chrome driver retain the session in multiple request使用 selenium 和 chrome 驱动程序的 Scrapy 在多个请求中保留会话
【发布时间】:2017-09-18 07:06:31
【问题描述】:

我正在使用带有 chrome 驱动程序的 Scrapy 和 Selenium 来抓取网站。我无法使用 Scrapy 抓取网站,只是因为网站中实施了一些保护机制,它给出了 404。当我将 selenium 与 scrapy 一起使用时,我能够访问页面 html。但问题是当我使用 selenium 时,我无法在通过 scrapy 访问的所有链接上保留会话 cookie。我想设置一些会话参数,如国家、语言等。

# -*- coding: utf-8 -*-
import scrapy
from selenium import webdriver
class SettingSpider(scrapy.Spider):
  name = 'setting'
  allowed_domains = ['example.com']
  start_urls = ['http://example.com/']

  def __init__(self):
      self.driver = webdriver.Chrome()

  def start_requests(self):
      url = 'http://www.example.com/'
      self.driver.get(response.url)
      yield scrapy.Request(url, self.parse)

  def parse(self, response):
      csrf = response.xpath('//input[@name="CSRFToken"]/@value').extract_first().strip()
      print('------------->' + csrf)
      url = 'http://www.example.com/settings'

      form_data = {'shippingCountry': 'ARE', 'language': 'en', 'billingCurrency': 'USD', 'indicativeCurrency': '',
                 'CSRFToken:': csrf}
      yield scrapy.FormRequest(url, formdata=form_data, callback=self.after_post)

  def getShippingCountry(self, response):
      country = response.css("a#shipping-country::text").extract_first().strip()
      return country

  def after_post(self, response):
      country = self.getShippingCountry(response)
      print('------------->' + country)

【问题讨论】:

  • 由于您使用的是单一 chrome,因此会话将保持不变。这不是问题,问题可能是您的命令顺序

标签: python scrapy


【解决方案1】:

你可以设置cookie

cookie = {‘name’ : ‘foo’, ‘value’ : ‘bar’}
driver.add_cookie(cookie)

如果您需要获取您的 cookie,您可以使用

driver.get_cookies()

更多信息请阅读this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    相关资源
    最近更新 更多