用Scrapy收集<select><option>值

2024-05-19 09:48:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我假装用Scrapy framework对这个页面顶部的下拉列表中的每一项进行爬网:https://www.anmp.pt/anmp/pro/mun1/mun101w3.php?cod=M2200。 然后,对于找到的每一项,我都会得到一个新页面,在那里我会得到更多的数据,这些数据必须填充到实例化的模型中型号.py 我能得到数据,但我一直不能把它放进数据库烧瓶。田地()我的模型。我在网上搜寻线索,但没有成功。 spider中的字段“contacto”只是收集以下两个字段之后的其他字段:

抱歉,名字是葡萄牙语的,但它是葡萄牙语应用程序!你知道吗

这是我的蜘蛛.py地址:

# -*- coding: utf-8 -*-
import scrapy
import urlparse
from scrapy.http import FormRequest
from scrapy.loader import ItemLoader
from municipios.items import Municipio
import time


class GetmunSpider(scrapy.Spider):
    name = 'getMun'
    allowed_domains = ['anmp.pt']
    start_urls = ['https://www.anmp.pt/anmp/pro/mun1/mun101w3.php?cod=M2200']

    def municipio_attr(self, response):
        municipios_url = response.xpath('//select/option/@value').extract()
        for municipio in municipios_url:
            full_url = ['https://www.anmp.pt/anmp/pro/mun1/{0}'.format(i) for i in municipios_url]      
            yield FormRequest.from_response(str(full_url), callback=self.parse) 

    def parse(self, response):
        #dados do municipio
        municipio = ItemLoader(item = Municipio(), response = response)
        municipio.add_xpath('nome', '//div[@class="sel3"]/text()'.extract())    
        municipio.add_xpath('pres_camara','//div[@class="f3"]/text()'
                 [3].extract().split(",")[0]
        municipio.add_xpath('pres_assembleia','//div[@class="f3"]/text()'
                 [4].extract().split(",")[0]
        municipio.add_xpath('contacto','//div[@class="sel2"]/text(
                 )').extract()
        municipio.add_value('endereco', " ".join(contacto)[:-42])
        municipio.add_value('telefone', contacto[2])
        municipio.add_value('fax', contacto[3])

        return Municipio.load_item()

这些是要填充的字段:

import scrapy
from scrapy.item import Item, Field

class Municipio(scrapy.Item):
    nome = scrapy.Field()
    pres_camara = scrapy.Field()
    pres_assembleia = scrapy.Field()
    endereco = scrapy.Field()
    telefone = scrapy.Field()
    fax = scrapy.Field()

Tags: fromimportaddpturlfieldresponseextract

热门问题