从头开始搭建爬虫环境
生活随笔
收集整理的這篇文章主要介紹了
从头开始搭建爬虫环境
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
第一步:安裝虛擬環(huán)境
- dirname 需自定義名稱
第二步:新建虛擬環(huán)境
我的當前環(huán)境默認為python3,所以新建python3的虛擬環(huán)境不用指明python的路徑
# 新建python3虛擬環(huán)境 >> mkvirtualenv dirname 復制代碼第三步:安裝其他依賴包
# 安裝scripy >> pip3 install scrapy # 安裝pymysql >> pip3 install pymysql # 安裝pymongo >> pip3 install pymongo 復制代碼錯誤一
安裝Scrapy時報錯Failed building wheel for Twisted
解決方案
點這里,去下載相應版本的twisted安裝即可
>> pip install Twisted-18.9.0-cp37-cp37m-win_amd64.whl 復制代碼錯誤二
ModuleNotFoundError: No module named 'win32api'
解決方案
>> pip3 install pywin32 復制代碼第四步:創(chuàng)建一個Scrapy項目并且連接數(shù)據(jù)庫
1.創(chuàng)建項目Test
scrapy startproject Test復制代碼2.創(chuàng)建爬蟲文件test
>> cd Test >> cd Test >> scrapy genspider test www.baidu.com 復制代碼3.在pipelines.py中創(chuàng)建2個類(mysql和mongo)
settings.py文件中的變量定義
# mongo相關變量 MONGODB_HOST = '127.0.0.1' MONGODB_PORT = 27017 MONGODB_DB = 'Tencent' MONGODB_SET = 'jobs'## mysql相關變量 MYSQL_HOST = 'localhost' MYSQL_PORT = 3306 MYSQL_USER = 'root' MYSQL_PWD = '123456' MYSQL_DB = 'Tencent' 復制代碼pipelines.py文件
# 這里的數(shù)據(jù)庫文件相關的配置變量都定義在settings.py里面 from Test.settings import * import pymongo import pymysql class mongoPipeline(object):def __init__(self):# 創(chuàng)建連接對象self.conn = pymongo.MongoClient(host=MONGODB_HOST, port=MONGODB_PORT)# 創(chuàng)建庫對象self.db = self.conn[MONGODB_DB]# 創(chuàng)建集合對象self.myset = self.db[MONGODB_SET]def process_item(self, item, spider):# 把一個item轉換為字段數(shù)據(jù)類型d =dict(item)self.myset.insert_one(d)return itemclass MysqlPipeline(object):def __init__(self):self.db = pymysql.connect(host=MYSQL_HOST,port = MYSQL_PORT,user = MYSQL_USER,password = MYSQL_PWD,database = MYSQL_DB)self.cursor = self.db.cursor()def process_item(self, item, spider):ins = 'insert into jobs(career,type,number,address,time,link) values(%s,%s,%s,%s,%s,%s)'L = [item['career'],item['type'],item['number'],item['address'],item['time'],item['link']]self.cursor.execute(ins,L)self.db.commit()return itemdef close_spider(self,spider):self.cursor.close()self.db.close()print("Mysql 數(shù)據(jù)庫斷開連接") 復制代碼4.在settings.py中設置好3個管道
ITEM_PIPELINES = {'Test.pipelines.TestPipeline': 300,'Test.pipelines.MongoPipeline':250,'Test.pipelines.MysqlPipeline':200 } 復制代碼5.在settings.py中設置好相關選項
# 是否遵守robots協(xié)議 ROBOTSTXT_OBEY = False # headers定義 DEFAULT_REQUEST_HEADERS = {"User-Agent": "Molliza/5.0",'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Accept-Language': 'en', } # 日志級別的定義 LOG_LEVEL = "WARNING" 復制代碼總結
以上是生活随笔為你收集整理的从头开始搭建爬虫环境的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux服务器---流量监控bandw
- 下一篇: 2、python机器学习基础教程——K近