scrapy yield scrappy.请求在每次迭代时都不调用parse函数

eagi6jfj  于 2023-01-17  发布在  其他
关注(0)|答案(1)|浏览(134)

在我的代码中,我必须在scraby类中使用函数。start_request从excel工作簿中获取数据,并将值赋给plate_num_xlsx变量。

def start_requests(self):
    df=pd.read_excel('data.xlsx')
    columnA_values=df['PLATE']
    for row in columnA_values:
        global  plate_num_xlsx
        plate_num_xlsx=row
        print("+",plate_num_xlsx)
        base_url =f"https://dvlaregistrations.dvla.gov.uk/search/results.html?search={plate_num_xlsx}&action=index&pricefrom=0&priceto=&prefixmatches=&currentmatches=&limitprefix=&limitcurrent=&limitauction=&searched=true&openoption=&language=en&prefix2=Search&super=&super_pricefrom=&super_priceto="
        url=base_url
        yield scrapy.Request(url,callback=self.parse)

但是,在每次迭代时,它都应该调用parseScrapy类的()方法,在该函数内部,每个新迭代的plate_num_xlsx值需要比较解析值,正如我在print语句之后所理解的,它首先获取所有值,分配它们,然后仅使用最后分配的值调用parse但是为了让我的爬行器正常工作,我需要在每次赋值时调用并使用def parse()中的值。代码如下;

import scrapy
from scrapy.crawler import CrawlerProcess
import pandas as pd

itemList=[]
class plateScraper(scrapy.Spider):
    name = 'scrapePlate'
    allowed_domains = ['dvlaregistrations.dvla.gov.uk']

    def start_requests(self):
        df=pd.read_excel('data.xlsx')
        columnA_values=df['PLATE']
        for row in columnA_values:
            global  plate_num_xlsx
            plate_num_xlsx=row
            print("+",plate_num_xlsx)
            base_url =f"https://dvlaregistrations.dvla.gov.uk/search/results.html?search={plate_num_xlsx}&action=index&pricefrom=0&priceto=&prefixmatches=&currentmatches=&limitprefix=&limitcurrent=&limitauction=&searched=true&openoption=&language=en&prefix2=Search&super=&super_pricefrom=&super_priceto="
            url=base_url
            yield scrapy.Request(url,callback=self.parse)

    def parse(self, response):

        for row in response.css('div.resultsstrip'):
            plate = row.css('a::text').get()
            price = row.css('p::text').get()
            a = plate.replace(" ", "").strip()
            print(plate_num_xlsx,a,a == plate_num_xlsx)
            if plate_num_xlsx==plate.replace(" ","").strip():
                item= {"plate": plate.strip(), "price": price.strip()}
                itemList.append(item)
                yield  item
            else:
                item = {"plate": plate_num_xlsx, "price": "-"}
                itemList.append(item)
                yield item

        with pd.ExcelWriter('output_res.xlsx', mode='r+',if_sheet_exists='overlay') as writer:
            df_output = pd.DataFrame(itemList)
            df_output.to_excel(writer, sheet_name='result', index=False, header=True)

process = CrawlerProcess()
process.crawl(plateScraper)
process.start()
jw5wzhpr

jw5wzhpr1#

以这种方式使用scrapy的全局变量是不起作用的,因为它是异步运行时行为,你可以选择将plate_num_xlsx变量作为回调关键字参数传递给请求对象本身。
例如:

plate_num_xlsx=row
            base_url =f"https://dvlaregistrations.dvla.gov.uk/search/results.html?search={plate_num_xlsx}&action=index&pricefrom=0&priceto=&prefixmatches=&currentmatches=&limitprefix=&limitcurrent=&limitauction=&searched=true&openoption=&language=en&prefix2=Search&super=&super_pricefrom=&super_priceto="
            url=base_url
            yield scrapy.Request(url,callback=self.parse, cb_kwargs={'plate_num_xlsx': plate_num_xlsx})


    def parse(self, response, plate_num_xlsx=None):
        for row in response.css('div.resultsstrip'):
            plate = row.css('a::text').get()
            price = row.css('p::text').get()
            ...

现在变量将作为参数包含到parse函数中。

相关问题