我正在使用Scrapy和Selenium以及Chrome驱动程序来搜索网站。我无法使用Scrapy刮网站,因为在网站上实施了一些404保护机制。当我使用selenium和scrapy时,我能够访问页面html。但问题是当我使用硒时,我无法在通过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)
答案 0 :(得分:0)
您可以设置Cookie
cookie = {‘name’ : ‘foo’, ‘value’ : ‘bar’}
driver.add_cookie(cookie)
如果您需要获取cookie,可以使用
driver.get_cookies()
有关详细信息,请参阅this