python爬蟲框架scrapy學習第二課
練習任務:爬取湖北成套招標公司的招標信息
- 第一步:新建一個爬蟲項目
scrapy startproject bids
- 在bids路徑下,創建一個基礎爬蟲類
scrapy genspider publicBids “hubeibidding.com”
- 確定要爬取的基礎數據,編寫item.py文件
class BidsItem(scrapy.Item):
#招標類型
bidsType = scrapy.Field()
#招標項目名稱
bidsName = scrapy.Field()
#招標項目鏈接
bidsLink = scrapy.Field()
#招標發佈時間
bidsTime = scrapy.Field()
- 編寫publicBids類,進行數據爬取
# -*- coding: utf-8 -*-
import scrapy
from bids.items import BidsItem
class PublicbidsSpider(scrapy.Spider):
"""
功能:練習爬取湖北省成套招標信息
"""
name = 'publicBids'
allowed_domains = ['hubeibidding.com']
url = "http://www.hubeibidding.com/plus/list.php?tid=4&TotalResult=10330&PageNo="
offset = 1
#起始url
start_urls = [url + str(offset)]
def parse(self, response):
for each in response.xpath("//ul[@class='e2']/li"):
item = BidsItem()
item['bidsType'] = each.xpath("./div/b/a/text()").extract()[0]
item['bidsName'] = each.xpath("./div/a/text()").extract()[0]
item['bidsLink'] = "http://www.hubeibidding.com/" + each.xpath("./div/a/@href").extract()[0]
item['bidsTime'] = each.xpath("./span/text()").extract()[1]
yield item
# if self.offset < 10:
# self.offset += 1
#yield scrapy.Request(self.url + str(self.offset), callback = self.parse)
上述註釋的代碼表示爬取多網頁的數據。這裏作爲例子,只爬取第一頁的數據。
- 將文件保存爲json格式,修改pipelines.py文件
import json
class BidsPipeline(object):
def __init__(self):
self.filename = open("bids.json", "wb")
def process_item(self, item, spider):
print("----------item------------\n")
print(item)
text = json.dumps(dict(item), ensure_ascii = False) + ",\n"
self.filename.write(text.encode("utf-8"))
return item
def close_spider(self, spider):
self.filename.close()
7.爲了能執行上述pipelines.py文件中定義的函數,需要修改settings.py文件,否則函數沒有執行,無法生成json文件。在文件末尾,增加
ITEM_PIPELINES = {
'bids.pipelines.BidsPipeline': 300,
}
- 在bids文件路徑下,執行爬取操作
scrapy crawl publicBids
- 在bids路徑下,生成bids.json文件