python爬虫✦基本知识与常用代码模块

本篇文章记录一些在我们使用python爬虫的过程中经常会用到的代码模块。

(1).爬虫代码思路+通用程序结构

class xxxSpider(object):
    def __init__(self):
        # 定义常用变量,url,headers及计数等
        
    def get_html(self):
        # 获取响应内容函数,使用随机User-Agent
    
    def parse_html(self):
        # 解析页面,提取数据
    
    def write_html(self):
        # 将提取的数据按要求保存,csv、MySQL数据库等
        
    def main(self):
        # 主函数,用来控制整体逻辑
        
if __name__ == '__main__':
	## 单线程
    spider = xxxSpider()
    spider.main()
    ## 多线程  from multiprocessing.pool import Pool
    pool = Pool()	# 括号里面为线程数量,默认为电脑核心数。
    pool.map(spider.main, [i for i in range(num)])	#i为main所需的传参

(1.1).定义多个User-Agent请求头,随机调用

#  代码实现
from fake_useragent import UserAgent
ua = UserAgent()
ua.random		# 获取随机请求头

(2)爬虫常用到的代码模块

(2.1).创建文件夹

函数传入文件名即可创建文件夹

'''如果文件夹不存在则先创建并返回,存在则直接返回'''
## name为文件夹名字的参数
def mkdir(name):
    if not os.path.exists(name):
        os.mkdir(name)
        return name
    else:
        return name

(2.2)保存数据

(2.2.1).保存数据到txt

## 1. 保存到txt
def save_file(name,content):
    with open("{}.txt".format(name),'w',encoding='utf-8') as f:
        f.write(content)	# 写入传进来的文件内容
        f.flush()
        print("保存成功")

(2.2.2).保存数据到csv

## 写入单行数据	(writerow([]))
import csv
def save_file():
	with open('test.csv', 'w',encoding='utf-8') as f:
    	writer = csv.writer(f)
    	writer.writerow(['hello world'])


## 写入多行数据	(writerows([(),(),()])
## 多行写入需要添加(newline=''),否则会在每行中间添加空白行 
import csv
def save_file():
	with open('test.csv', 'w', newline='',encoding='utf-8') as f:
    	writer = csv.writer(f)
    	writer.writerows([('小蔡', '22'), ('sunrisecai', '22')])

(2.2.3)建立连接到mysql + 保存数据 普通版

import pymysql

# 创建2个对象
db = pymysql.connect('localhost','root','123456','<数据库名>',charset='utf8')
cursor = db.cursor()

# 执行SQL命令并提交到数据库执行
# execute()方法第二个参数为列表传参补位

cursor.execute('insert into <数据表名> values(%s,%s)',['月光宝盒','周星驰'])
db.commit()	# 提交操作

# 关闭游标、关闭数据库
cursor.close()
db.close()

(2.2.3).建立连接到mysql + 保存数据 高效版

相比普通版的 execute更改为executemany

import pymysql

# 创建2个对象
db = pymysql.connect('localhost', 'root', '123456', 'table', charset='utf8')
cursor = db.cursor()

# 抓取的数据
film_list = [('月光宝盒', '周星驰', '1994'), ('大圣娶亲', '周星驰', '1994')]

# 执行SQL命令并提交到数据库执行
# execute()方法第二个参数为列表传参补位
cursor.executemany('insert into filmtab values(%s,%s,%s)', film_list)
db.commit()

# 关闭
cursor.close()
db.close()

(2.2.4).建立连接到MongoDB + 保存数据

import pymongo
## 共三步 (1.连接对象 2.库连接 3.集合对象)
# 1.数据库连接对象
conn=pymongo.MongoClient('localhost',27017)
# 2.库对象
db = conn['库名']
# 3.集合对象
myset = db['集合名']
# 4.插入数据
myset.insert_one({"name":"小蔡"})	#{字典}

(2.2.4)MongoDB常用操作

# 1.查看所有数据库
	show dbs
# 2.选择数据库
	use <数据库名>
# 3.查看所有集合
	show collections
# 4.查看集合内容
	db.collection(集合).find()
# 5.删除当前数据库
	db.dropDatabase()
# 6.删除集合
	db.collection.drop()

(3)获取当前年月日时分秒

获取当前年月日

now_time = time.strftime('%Y-%m-%d',time.localtime(time.time()))

获取当前年月日时分秒

now_time = time.strftime('%Y-%m-%d %H:%M:%S')

(100).持续更新

发布了34 篇原创文章 · 获赞 210 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_45081575/article/details/98938349