Skip to main content
 首页 » 编程设计

python之选择正确的 URL 来记录爬虫

2025年01月19日11sharpest

This website需要登录才能访问我要抓取的信息。 我的选择器在我用 scrapy shell 检查时工作。但我想我错过了登录部分的一些东西,因为当我运行我的脚本时,我无法访问信息。

这是我的脚本:

class StartupsSpider(scrapy.Spider): 
    name = "alloweb" 
 
   login_page = 'http://www.alloweb.org/annuaire-startups/referencer-une-entreprise/' 
   start_urls = ['http://www.alloweb.org/annuaire-startups/annuaire-start-ups/'] 
 
 
 
   def init_request(self): 
       yield Request(url=self.login_page, callback=self.login) 
 
   def login(self, response): 
       return scrapy.FormRequest.from_response( 
                response, 
                formxpath=FORM_SELECTOR, 
                formdata={'login': 'xxx', 'password': 'xxx'}, 
                callback=self.parse, 
                ) 
 
 
   def parse(self, response):         
       for startups in response.xpath(SET_SELECTOR): 
 
 
           for company_link in response.xpath(COMPANY_SELECTOR).extract(): 
               yield scrapy.Request( 
                   format(company_link.strip("/")), 
                   meta={'cookiejar':company_link}, 
                   callback=self.parse_company_profile, 
               ) 
 
 
        next_page = startups.css(NEXT_PAGE_SELECTOR).extract_first() 
        if next_page: 
            yield scrapy.Request( 
                response.urljoin(next_page), 
                meta={'cookiejar': response.meta['cookiejar']}, 
                callback=self.parse, 
            ) 
 
   def parse_company_profile(self, response): 
       for startups in response.xpath(SET_SELECTOR2): 
 
         yield { 
            'name': startups.xpath(NAME_SELECTOR).extract_first(), 
            'description': startups.xpath(DESCR_SELECTOR).extract_first(), 
            'website':startups.xpath(WEBSITE_SELECTOR).extract_first(), 
            'socialmedia':startups.xpath(SM_SELECTOR).extract(), 
            'creator':startups.xpath(CREATOR_SELECTOR).extract(), 
            'hub':startups.xpath(HUB_SELECTOR).extract_first(), 
            'phone':startups.xpath(PHONE_SELECTOR).extract(), 
            'email':startups.xpath(EMAIL_SELECTOR).extract(),    
        } 

请您参考如下方法:

您的登录代码根本没有执行。
init_request() 方法只被 Scrapy 的 InitSpider 使用(文档中似乎没有提到)。

class itself有很好的文档记录,因此您应该不会在创建工作蜘蛛时遇到麻烦。

由于 InitSpider 实际上并没有做太多事情,另一种可能性是使用登录 url 作为起始 url 重写您的蜘蛛,并自己创建所需的请求序列。