用Scrapy遍历表行

2024-10-03 21:36:19 发布

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

有没有可能扫描表中的一行,只改变列,得到一系列的数字。我目前正在使用许多变量。你知道吗

示例:

response.xpath('/html/body/div/table/tr[6]/td[counter in range 2 - 9]/p/span/text()').extract()

代码:

class MainSpider(scrapy.Spider):
    name = "main-spider"
    start_urls = ['http://www.institutosantatereza.com.br/boletins/turma_3_ano_ensino_medio/1652.htm']


    def parse(self, response):
        nome = response.xpath('/html/body/div/table/tr[2]/td[2]/p/b/span/text()').extract()
        serie = response.xpath('/html/body/div/table/tr[2]/td[7]/p/b/span/text()').extract()


        portugues1 = response.xpath('/html/body/div/table/tr[6]/td[2]/p/span/text()').extract()
        portugues2 = response.xpath('/html/body/div/table/tr[6]/td[3]/p/span/text()').extract()
        portuguesMedia1 = response.xpath('/html/body/div/table/tr[6]/td[4]/p/span/text()').extract()


        yield{
            "nome": nome[0],
            "serie": serie[0],
            "url": response.url,
            "disciplinas":{
                "portugues":{
                    'nota1': portugues1[0],
                    'nota2': portugues2[0],
                    'media1': portuguesMedia1[0], 
                }
            }
        }

Tags: textdivresponsehtmltableextractbodyxpath
1条回答
网友
1楼 · 发布于 2024-10-03 21:36:19

无需使用许多变量:

yield{
    "nome": nome[0],
    "serie": serie[0],
    "url": response.url,
    "disciplinas":{
        "portugues":{
            'nota1': response.xpath('/html/body/div/table/tr[6]/td[2]/p/span/text()').extract_first(), # or .get()
            'nota2': response.xpath('/html/body/div/table/tr[6]/td[3]/p/span/text()').get(), # or .extract_first()
        }
    }
}

相关问题 更多 >