実装手順
- クローラプロジェクトを作成します。
- データモデルの要件定義によると、
- 爬虫類を達成
- クロールデータ保存
- アドレス抗登るIPにダウンロードミドルウェアIPランダムユーザーエージェントとエージェントを実装
爬虫類を達成するための具体的な手順
- URL = URL ' https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=6899&pn=20&rn=10&ie=utf-8&oe=utf-8&query=不誠実な債務者 '
- 失敗した場合、テストは、あなたがリクエストヘッダーを設定する必要があるかもしれません
- リクエストメソッドget
- パラメータ
- ユーザエージェントリファラー要求ヘッダー
- データの数を返します。
- 反転する方法
- 時々、URLのページを得ることなく、パラメータページの要求に応じては、ループの要求であってもよいです
- URL = URL ' https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=6899&pn=20&rn=10&ie=utf-8&oe=utf-8&query=不誠実な債務者 '
不正リスト情報の保存
データベースを作成し、テーブルを作成
構成データベース情報の設定で
- ホスト、ポート、DB、ユーザー、パスワード
パイプラインを実現
open_spiderで、データベース接続の確立、アクセスカーソル
def open_spider(self, spider): """不用做判断,因为三只爬虫的爬取结果全部放到同一个数据库里边""" # 创建数据库连接 self.connection = pymysql.connect(host=MYSQL_HOST, port=MYSQL_PORT, db=MYSQL_DB, user=MYSQL_USER, password=MYSQL_PASSWORD) # 获取游标 self.cursor = self.connection.cursor()
近くにカーソルでclose_spiderでは、接続を閉じます
def close_spider(self, spider): # 关闭游标 self.cursor.close() # 关闭连接 self.connection.close()
process_itemでは、データが存在しない場合は、データを保存します
def process_item(self, item, spider): # 存储过程,最重要是判断数据是否已经存在 # 判断数据是否已经存在 if item['age'] == 0: select_count_sql = "select count(1) from dishonest where name='{}' and area='{}'".format(item['name'], item['area']) else: select_count_sql = "select count(1) from dishonest where card_num='{}'".format(item['card_num']) # 执行查询 self.cursor.execute(select_count_sql) count = self.cursor.fetchone()[0] # 游标会获取的结果是列表形式 # 根据查询结果,决定是否插入数据 if count == 0: keys, values = zip(*dict(item).items()) insert_sql = 'insert into dishonest ({}) values ({})'.format( ','.join(keys), ','.join(['%s']*len(values)) ) self.cursor.execute(insert_sql,values) self.connection.commit() spider.logger.info('插入数据') else: spider.logger.info('数据重复')
settings.pyで開くパイプ
約束のリストをクロール
おすすめ
転載: www.cnblogs.com/hui-code/p/12030353.html
ランキング