python - 如何遍历scrapy spider中的参数列表?
问题描述
嗨,我正在尝试在 scrapy spider 命令中传递参数列表。我能够为 1 个参数运行它。但无法为参数列表执行此操作。请帮忙。这是我尝试过的。
# -*- coding: utf-8 -*-
import scrapy
import json
class AirbnbweatherSpider(scrapy.Spider):
name = 'airbnbweather'
allowed_domains = ['www.wunderground.com']
def __init__(self,geocode ):
self.geocode = geocode.split(',')
pass
def start_requests(self):
yield scrapy.Request(url="https://api.weather.com/v3/wx/forecast/daily/10day?apiKey=6532d6454b8aa370768e63d6ba5a832e&geocode={0}{1}{2}&units=e&language=en-US&format=json".format(self.geocode[0],"%2C",self.geocode[1]))
def parse(self, response):
resuturant = json.loads(response.body)
yield {
'temperatureMax' : resuturant.get('temperatureMax'),
'temperatureMin' : resuturant.get('temperatureMin'),
'validTimeLocal' : resuturant.get('validTimeLocal'),
}
我可以使用这个命令运行它
scrapy crawl airbnbweather -o BOSTON.json -a geocode="42.361","-71.057"
它工作正常。但是我如何遍历地理编码列表?
list = [("42.361","-71.057"),("29.384","-94.903"),("30.384", "-84.903")]
解决方案
您只能将字符串用作蜘蛛参数(https://docs.scrapy.org/en/latest/topics/spiders.html#spider-arguments),因此您应该将列表作为字符串传递,并在您的代码。以下似乎可以解决问题:
import scrapy
import json
import ast
class AirbnbweatherSpider(scrapy.Spider):
name = 'airbnbweather'
allowed_domains = ['www.wunderground.com']
def __init__(self, geocode, *args, **kwargs):
super().__init__(*args, **kwargs)
self.geocodes = ast.literal_eval(geocode)
def start_requests(self):
for geocode in self.geocodes:
yield scrapy.Request(
url="https://api.weather.com/v3/wx/forecast/daily/10day?apiKey=6532d6454b8aa370768e63d6ba5a832e&geocode={0}{1}{2}&units=e&language=en-US&format=json".format(geocode[0],"%2C",geocode[1]))
然后,您可以像这样运行爬虫:
scrapy crawl airbnbweather -o BOSTON.json -a geocodes='[("42.361","-71.057"),("29.384","-94.903"),("30.384", "-84.903")]'
推荐阅读
- winforms - Xaxis min 和 max Range 设置后的自定义标签 FromPosition 和 ToPosition 的 Windows
- python - Django CMS - 无法修改新添加网页的结构
- angular - 回答问题时如何使用 [style.border] 更改边框样式?
- styles - 转义脚本以隐藏/显示 textarea
- python - pyodbc 操作错误 08001 ssl 安全错误
- javascript - 获取 Formik 验证本年及以上
- ubuntu - discord.js ubuntu } catch { SyntaxError: Unexpected token {
- powershell - TagLib - 从 MP3 中提取专辑封面 (Powershell)
- php - 滚动条不可滚动页脚占用 Wordpress 主题中的页面
- node.js - 无法测试 mongo 聚合 MongoError:无法识别的管道阶段名称:'$set'