使用scrapy爬取某城市天气预报 编写爬虫项目,从 https://www.tianqi.com 网站爬取一个城市(城市名通过input输入)的天气预报数据,并把爬取到的天气数据写入本地文本文件weather.txt。提示: (1)安装Python扩展库scrapy,创建爬虫项目,将需要获取的字段名填写进去; (2)将爬取到的数据写入文件weather.txt;
时间: 2024-03-04 18:51:49 浏览: 47
好的,以下是一个使用Scrapy爬取某城市天气预报并将结果写入本地文本文件的示例代码。请按照以下步骤进行操作:
1. 创建Scrapy项目
在命令行中执行以下命令,创建一个名为"weather"的Scrapy项目:
```
scrapy startproject weather
```
2. 创建Spider
在命令行中执行以下命令,创建一个名为"city_weather"的Spider:
```
cd weather
scrapy genspider city_weather tianqi.com
```
这将在spiders目录下创建一个名为"city_weather.py"的文件,其中包含一个名为"CityWeatherSpider"的Spider类。
3. 编写Spider代码
打开"city_weather.py"文件,将以下代码复制并粘贴到文件中:
```python
import scrapy
class CityWeatherSpider(scrapy.Spider):
name = 'city_weather'
allowed_domains = ['tianqi.com']
def start_requests(self):
city = input('请输入城市名:')
url = 'https://www.tianqi.com/{}/'.format(city)
yield scrapy.Request(url, callback=self.parse)
def parse(self, response):
city = response.xpath('//div[@class="city"]/h2/text()')[0].extract()
date = response.xpath('//div[@class="date"]/text()')[0].extract()
weather = response.xpath('//div[@class="weather"]/text()')[0].extract()
temperature = response.xpath('//div[@class="temperature"]/text()')[0].extract()
wind_direction = response.xpath('//div[@class="wind"]/span[1]/text()')[0].extract()
wind_speed = response.xpath('//div[@class="wind"]/span[2]/text()')[0].extract()
with open('weather.txt', 'w', encoding='utf-8') as f:
f.write(city + '\n')
f.write(date + '\n')
f.write(weather + '\n')
f.write(temperature + '\n')
f.write(wind_direction + '\n')
f.write(wind_speed + '\n')
```
这段代码中,我们首先在start_requests()方法中获取用户输入的城市名,并构造相应的URL。然后,我们使用Scrapy库的Request类发送HTTP请求,获取HTML文档。在parse()方法中,我们使用XPath表达式提取城市名称、日期、天气情况、温度、风向和风速等信息,并将这些信息写入本地文件中。
4. 运行Spider
在命令行中执行以下命令,运行Spider:
```
scrapy crawl city_weather
```
按照提示输入城市名后,程序将自动爬取相应城市的天气预报数据,并将结果写入本地文件"weather.txt"中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)