import scrapy class WeatherSpider(scrapy.Spider): name = 'weather_spider' allowed_domains = ['tianqi.com'] start_urls = ['https://www.tianqi.com/'] def parse(self, response): # 获取城市名称 city = response.xpath('//div[@class="city"]/h2/text()')[0].extract() # 获取日期 date = response.xpath('//div[@class="weather"]/ul/li[1]/p[1]/text()')[0].extract() # 获取天气情况 weather = response.xpath('//div[@class="weather"]/ul/li[1]/p[2]/text()')[0].extract() # 获取温度 temperature = response.xpath('//div[@class="weather"]/ul/li[1]/p[3]/text()')[0].extract() # 获取风向 wind_direction = response.xpath('//div[@class="weather"]/ul/li[1]/p[4]/span[1]/text()')[0].extract() # 获取风速 wind_speed = response.xpath('//div[@class="weather"]/ul/li[1]/p[4]/span[2]/text()')[0].extract() # 将数据写入本地文件 with open('weather.txt', 'w', encoding='utf-8') as f: f.write('城市:{}\n'.format(city)) f.write('日期:{}\n'.format(date)) f.write('天气:{}\n'.format(weather)) f.write('温度:{}\n'.format(temperature)) f.write('风向:{}\n'.format(wind_direction)) f.write('风速:{}\n'.format(wind_speed))
时间: 2024-02-06 18:04:02 浏览: 22
这是一个使用 Scrapy 爬取天气信息并将数据写入本地文件的代码。首先设置了要爬取的网站域名和起始 URL,然后在 parse 方法中使用 XPath 获取城市名称、日期、天气情况、温度、风向和风速等信息,并将这些信息写入本地文件 weather.txt 中。如果需要运行这个爬虫,可以在命令行中进入该代码所在目录,然后执行 scrapy crawl weather_spider 命令即可。当然,在执行之前还需要安装 Scrapy 并创建一个 Scrapy 项目。
相关问题
import scrapy class WeatherSpider(scrapy.Spider): name = 'weather' allowed_domains = ['tianqi.com'] start_urls = ['https://www.tianqi.com/'] def parse(self, response): city = 'beijing' # 自选城市 url = f'https://tianqi.com/{city}/' yield scrapy.Request(url, callback=self.parse_weather) def parse_weather(self, response): date = response.css('.week>p::text').get() weather = response.css('.weather span::text').get() temperature = response.css('.weather .temp::text').get() humidity = response.css('.weather .shidu::text').get() wind = response.css('.weather .zi .name::text').get() with open('weather.txt', 'a', encoding='utf-8') as f: f.write(f'{date} {weather} {temperature} {humidity} {wind}\n'上面的代码运行后在cmd中显示<403https://www.tianqi.com/>:HTTP status code is not handled or not allowed如何解决)
在你的代码中,你请求的 URL 是 https://tianqi.com/beijing/,而不是 https://www.tianqi.com/,这可能是引起 403 错误的原因之一。
此外,你需要在请求头中添加一个 User-Agent 字段,模拟一个浏览器的请求,以避免被网站反爬虫机制拦截。你可以在请求头中添加类似以下代码的字段:
```
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
yield scrapy.Request(url, headers=headers, callback=self.parse_weather)
```
这里模拟的 User-Agent 是 Chrome 的一个版本,你可以根据需要更改。
最后,你可以添加一个错误处理函数,用于处理发生错误时的情况。你可以在 Spider 类中添加以下代码:
```
def handle_error(self, failure):
self.logger.error(repr(failure))
```
然后在 Request 中添加 errback 参数,将错误处理函数传入即可:
```
yield scrapy.Request(url, headers=headers, callback=self.parse_weather, errback=self.handle_error)
```
这样就可以在发生错误时打印出错误信息了。
用python实现对https://lishi.tianqi.com/beijing/202211.html的运用scrapy框架的爬虫并将数据存入数据库
好的,以下是使用Scrapy框架爬取https://lishi.tianqi.com/beijing/202211.html并将数据存入数据库的步骤:
1. 创建Scrapy项目
在命令行中输入以下命令:
```
scrapy startproject lishi
```
这将创建一个名为`lishi`的Scrapy项目。
2. 创建Spider
在`lishi/spiders`目录下创建一个名为`lishi_spider.py`的文件,并添加以下代码:
```python
import scrapy
from lishi.items import LishiItem
class LishiSpider(scrapy.Spider):
name = "lishi"
allowed_domains = ["lishi.tianqi.com"]
start_urls = ["https://lishi.tianqi.com/beijing/202211.html"]
def parse(self, response):
item = LishiItem()
item['date'] = response.css('ul.tqtongji2 li:nth-child(1)::text').get()
item['max_temp'] = response.css('ul.tqtongji2 li:nth-child(2)::text').get()
item['min_temp'] = response.css('ul.tqtongji2 li:nth-child(3)::text').get()
item['weather'] = response.css('ul.tqtongji2 li:nth-child(4)::text').get()
item['wind'] = response.css('ul.tqtongji2 li:nth-child(5)::text').get()
yield item
```
在这个Spider中,我们定义了`name`属性为`lishi`,并设置`allowed_domains`为`lishi.tianqi.com`,`start_urls`为要爬取的网址。`parse()`方法是Scrapy默认的回调函数,用于处理`start_urls`中的响应。在这个方法中,我们使用CSS选择器选择天气历史数据,并将其输出为`LishiItem`对象。
3. 创建Item
在`lishi`目录下创建一个名为`items.py`的文件,并添加以下代码:
```python
import scrapy
class LishiItem(scrapy.Item):
date = scrapy.Field()
max_temp = scrapy.Field()
min_temp = scrapy.Field()
weather = scrapy.Field()
wind = scrapy.Field()
```
`LishiItem`是我们定义的一个Scrapy Item,用于存储天气历史数据。
4. 配置数据库
在`settings.py`文件中添加以下代码:
```python
ITEM_PIPELINES = {
'lishi.pipelines.LishiPipeline': 300,
}
MONGODB_SERVER = "localhost"
MONGODB_PORT = 27017
MONGODB_DB = "weather"
MONGODB_COLLECTION = "lishi"
```
这里我们启用了一个名为`LishiPipeline`的Item Pipeline,并配置了MongoDB数据库的连接信息。
5. 创建Pipeline
在`lishi`目录下创建一个名为`pipelines.py`的文件,并添加以下代码:
```python
import pymongo
class LishiPipeline(object):
def __init__(self, mongo_uri, mongo_db, mongo_collection):
self.mongo_uri = mongo_uri
self.mongo_db = mongo_db
self.mongo_collection = mongo_collection
@classmethod
def from_crawler(cls, crawler):
return cls(
mongo_uri=crawler.settings.get('MONGODB_SERVER'),
mongo_db=crawler.settings.get('MONGODB_DB'),
mongo_collection=crawler.settings.get('MONGODB_COLLECTION')
)
def open_spider(self, spider):
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db]
def close_spider(self, spider):
self.client.close()
def process_item(self, item, spider):
self.db[self.mongo_collection].insert_one(dict(item))
return item
```
这里我们定义了一个名为`LishiPipeline`的Item Pipeline,用于将爬取到的数据存入MongoDB数据库中。
6. 运行Spider
在命令行中,进入`lishi`项目目录,输入以下命令:
```
scrapy crawl lishi
```
这会运行我们刚刚创建的Spider,并将结果存入MongoDB数据库中。
7. 结果验证
在MongoDB数据库中,可以查询到我们爬取到的天气历史数据。