利用scrapy爬取南昌天气预报
时间: 2023-08-02 19:40:37 浏览: 240
好的,以下是利用Scrapy爬取南昌天气预报的步骤:
1. 创建Scrapy项目:在命令行中输入 `scrapy startproject weather_crawler`,创建一个名为weather_crawler的Scrapy项目。
2. 创建Spider:进入项目目录,使用命令 `scrapy genspider nanchang www.nmc.cn` 创建一个名为nanchang的Spider,用于爬取南昌的天气预报信息。
3. 编写Spider:打开nanchang.py文件,在start_urls中添加要爬取的页面URL,使用XPath或CSS选择器提取所需信息,并将提取到的数据存储到Item中。
4. 编写pipelines:在pipelines.py文件中编写数据处理和存储的代码,例如将数据存储到本地文件或数据库中。
5. 启动Spider:在命令行中输入 `scrapy crawl nanchang` 启动Spider,等待程序爬取数据并保存到本地文件或数据库中。
希望以上步骤能够帮助您成功爬取南昌的天气预报信息。
相关问题
python使用scrapy爬取南京天气预报
好的,以下是一个简单的 Scrapy 爬取南京天气预报的示例:
1. 创建 Scrapy 项目
在命令行中输入以下命令:
```
scrapy startproject nanjing_weather
cd nanjing_weather
```
2. 创建爬虫
在命令行中输入以下命令:
```
scrapy genspider nanjing www.weather.com.cn
```
这将在 `nanjing_weather/spiders` 目录下创建一个名为 `nanjing.py` 的文件,用于定义爬虫。
3. 编写爬虫代码
打开 `nanjing.py` 文件,将以下代码粘贴到文件中:
```python
import scrapy
class NanjingWeatherSpider(scrapy.Spider):
name = 'nanjing'
allowed_domains = ['www.weather.com.cn']
start_urls = ['http://www.weather.com.cn/weather/101190101.shtml']
def parse(self, response):
# 获取天气信息
weather_info = response.xpath('//div[@id="7d"]/ul/li')
for info in weather_info:
date = info.xpath('h1/text()').get()
weather = info.xpath('p[@class="wea"]/text()').get()
temperature = info.xpath('p[@class="tem"]/span/text()').get() + info.xpath('p[@class="tem"]/i/text()').get()
wind = info.xpath('p[@class="win"]/i/text()').get()
yield {
'city': '南京',
'date': date,
'weather': weather,
'temperature': temperature,
'wind': wind,
}
```
以上代码定义了一个名为 `NanjingWeatherSpider` 的爬虫,首先在 `start_urls` 中定义了南京天气预报页面的链接,然后在 `parse` 方法中获取天气信息,并将数据以字典的形式返回。
4. 运行爬虫
在命令行中输入以下命令:
```
scrapy crawl nanjing -o nanjing_weather.json
```
这将运行爬虫并将爬取到的数据保存到 `nanjing_weather.json` 文件中。
以上就是一个简单的 Scrapy 爬取南京天气预报的示例。
利用scrapy爬取某城市天气预报的代码
下面是利用Scrapy爬取某城市天气预报的代码示例:
```python
import scrapy
class WeatherSpider(scrapy.Spider):
name = "weather"
start_urls = ["http://www.weather.com.cn/weather/101010100.shtml"]
def parse(self, response):
city = response.css(".crumbs.fl a::text").get()
date = response.css("#7d .t::text").getall()
weather = response.css("#7d .wea::text").getall()
temperature_high = response.css("#7d .tem span::text").getall()[::2]
temperature_low = response.css("#7d .tem span::text").getall()[1::2]
wind_direction = response.css("#7d .win i::text").getall()[::2]
wind_strength = response.css("#7d .win i::text").getall()[1::2]
for i in range(7):
yield {
"city": city,
"date": date[i],
"weather": weather[i],
"temperature_high": temperature_high[i],
"temperature_low": temperature_low[i],
"wind_direction": wind_direction[i],
"wind_strength": wind_strength[i]
}
```
说明:
- `name`:爬虫的名称。
- `start_urls`:爬虫的起始URL。
- `parse`:解析响应的方法。
- `response.css()`:使用CSS选择器获取页面元素。
- `yield`:返回一个字典,包含天气信息。
在终端中运行以下命令即可启动爬虫:
```bash
scrapy runspider weather_spider.py -o weather.csv
```
其中,`-o` 参数指定了输出文件的格式和路径。这里我们输出为 CSV 格式的文件 `weather.csv`。
阅读全文
相关推荐
















