天氣后報網——資料爬取(Scrapy框架)
1.創建天氣后報網爬蟲
在開始編程之前,我們首先要根據專案需求對天氣后報網站進行分析,目標是提取2016-2020年每個城市的每天的溫度、天氣狀況、風力風向等資料,首先來到天氣后報網(http://www.tianqihoubao.com/lishi/),如圖1所示,

圖 1
可以看到串列中每個省份下的城市資訊,以北京市為例,點擊進去,進入二級頁面,

、 圖 2
以2011年1月北京天氣為例,進入三級頁面(詳情頁面),其中可以看到日期、天氣狀況、氣溫、風力風向等所需的資訊,

圖 3
以上將整個爬蟲專案的流程分析完成,編程可以開始了,首先在命令列中切換到用于存盤專案的路徑,然后輸入下面命令創建爬蟲專案和爬蟲模塊:
1 scrapy startproject tqhbCrawl 2 cd tqhbCrawl 3 scrapy genspider -t crawl tqhb_spider "tianqihoubao.com/lishi/"
2.定義Item
創建完工程后,首先要做的是定義Item,確定我們需要提取的結構化資料,代碼如下:
1 import scrapy 2 3 class TqhbItem(scrapy.Item): 4 # 城市名 5 city_name = scrapy.Field() 6 # 日期 7 date = scrapy.Field() 8 # 天氣狀況 9 state = scrapy.Field() 10 # 風力風向 11 wind = scrapy.Field() 12 #溫度 13 temp = scrapy.Field()
3.撰寫爬蟲模塊
通過genspider命令已經創建了一個基于CrawlSpider 類的爬蟲模板,類名稱為 TqhbSpiderSpider,下面進行開始頁面決議,主要有兩個方法,detail_url 方法用于決議圖2所示的串列資訊,抽取三級頁面url的鏈接資訊,parse 方法用于抽取圖3所示的基本的資訊,對于二級頁面鏈接的抽取,則是在 rules 中定義抽取規則(只能抽取start_urls中符合 rules 的鏈接,故需要使用 detail_url 方法構造三級鏈接 TqhbSpiderSpider完整代碼如下:
1 class TqhbSpiderSpider(CrawlSpider): 2 name = 'tqhb_spider' 3 allowed_domains = ['tianqihoubao.com'] 4 start_urls = ['http://tianqihoubao.com/lishi'] 5 6 rules = ( 7 Rule(LinkExtractor(allow='.+lishi.+html'),callback="detail_url",follow=False), 8 ) 9 10 def detail_url(self, response): 11 base_url = "http://tianqihoubao.com" 12 divs = response.xpath("//div[@class='box pcity']")[5:9] 13 detail_urls = divs.xpath(".//a/@href").getall() 14 for detail_url in detail_urls: 15 yield scrapy.Request(base_url+detail_url,callback=self.parse) 16 17 def parse(self, response): 18 # 獲取 城市 日期 天氣狀態 氣溫 風力風向資訊 19 city_name = response.xpath('//div[@id="s-calder"]/h2/text()').get() 20 city_name = ''.join(re.findall(r'[^0-9]', city_name))[:-9] 21 trs = response.xpath("//tr")[1:] 22 for tr in trs: 23 tds = tr.xpath(".//td") 24 date = tds[0].xpath(".//text()").getall() 25 date = "".join(''.join(date).split()) 26 state = tds[1].xpath(".//text()").getall() 27 state = "".join(''.join(state).split()) 28 temp = tds[2].xpath(".//text()").getall() 29 temp = "".join(''.join(temp).split()) 30 wind = tds[3].xpath(".//text()").getall() 31 wind = "".join(''.join(wind).split()) 32 item = TqhbItem( 33 city_name=city_name, 34 date=date, 35 state=state, 36 temp=temp, 37 wind=wind) 38 yield item
4.Pipeline
下面開始撰寫Pipeline,主要完成 Item 到 SCV 表的存盤,
1 class TqhbPipeline(object): 2 def __init__(self): 3 self.fp = open("tqhb.csv", 'wb') 4 self.exporter = CsvItemExporter( 5 self.fp, encoding='utf-8') 6 7 def open_spider(self, spider): 8 print("爬蟲開始....") 9 10 11 def process_item(self, item, spider): 12 self.exporter.export_item(item) 13 return item 14 15 def close_spider(self, spider): 16 self.fp.close() 17 print("爬蟲結束了....")
最后在 settings 中將如下代碼的注釋取消掉:
1 ITEM_PIPELINES = { 2 'tqhb.pipelines.TqhbPipeline': 300, 3 }
5.應對反爬蟲機制
為了不被反爬蟲機制檢測到,主要采用了偽造隨機 ‘User-Agent’、自動限速、禁用 robots.txt 等措施,
1.偽造隨機 User-Agent,撰寫middlewares.py
1 import random 2 3 class TqhbDownloaderMiddleware(object): 4 user_agents = [ 5 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.23 Safari/537.36", 6 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36", 7 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36", 8 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.27 Safari/537.36", 9 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36", 10 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4280.87 Safari/537.36", 11 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.20 Safari/537.36", 12 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 Edg/87.0.664.75", 13 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 Edg/89.0.774.57", 14 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 Edg/89.0.774.54", 15 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 Edg/89.0.774.50", 16 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 Edg/90.0.818.6", 17 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 Edg/90.0.818.8", 18 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 Edg/90.0.818.14" 19 ] 20 def process_request(self,request,spider): 21 user_agent = random.choice(self.user_agents) 22 request.headers["User-Agent"]=user_agent
并使用該中間件設定DEFAULT_REQUEST_HEADERS:
1 DOWNLOADER_MIDDLEWARES = { 2 'tqhb.middlewares.TqhbDownloaderMiddleware': 543, 3 } 4 5 DEFAULT_REQUEST_HEADERS = { 6 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 7 'Accept-Language': 'en', 8 }
2.自動限速設定:
1 DOWNLOAD_DELAY = 1 2 AUTOTHROTTLE_ENABLED = True 3 AUTOTHROTTLE_START_DELAY = 5 4 AUTOTHROTTLE_MAX_DELAY = 60
3.禁用禁用 robots.txt
1 ROBOTSTXT_OBEY = False
6.運行專案
在專案檔案下創建start.py,代碼如下:
1 from scrapy import cmdline 2 3 cmdline.execute("scrapy crawl tqhb_spider".split())

存盤效果
以上所有代碼皆可在本人github賬號上下載: https://github.com/chyhoo/2016-2020Chinese-Weather-Analysis
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/278355.html
標籤:Python
