用面对对象的方法抓取腾讯招聘页面的招聘信息数据,并将抓取的数据存入MYSQL数据库中.*
1.创建爬虫类–>创建类属性
class TencentCareerSpider:
url = 'https://careers.tencent.com/tencentcareer/api/post/Query?timestamp=1731910332172&countryId=&cityId=&bgIds=&productId=&categoryId=&parentCategoryId=&attrId=&keyword=python&pageIndex={}&pageSize=10&language=zh-cn&area=cn' # from 1 to ----63
headers = {
'User-Agent':UserAgent().random,
'referer':'https://careers.tencent.com/search.html?keyword=python'
}
将url和headers设置成类属性,而不是放在__init__中作为初始化实例属性,
2.创建爬虫类–>创建初始化方法
def __init__(self): # 连接数据库
self.db = pymysql.connect(host='localhost',user='root',password='123456',database='tencent_career')
self.cursor = self.db.cursor()
由于数据库的连接和游标的创建都只执行一次,所以放在初始化方法中,每次实例化的时候初始化创建一次.
3.创建爬虫类–>创建数据库关闭方法
def __del__(self):
self.cursor.close()
self.db.close()
__del__()方法是类内置的方法,作用为:当程序执行完成后关闭时,会自动调用该方法,将游标关闭和数据库关闭的方法放在__del__()方法中,当程序执行完成后,会自动调用关闭的方法.
4.创建爬虫类–>创建数据表方法
def create_table(self):
sql = """
create table if not exists tencent_career_table(
id int primary key auto_increment,
work_name varchar(200) not null,
country_name varchar(100),
city_name varchar(100),
category_name varchar(100),
responsibility text,
update_time varchar(100)
)
"""
try:
self.cursor.execute(sql)
except Exception as e:
print('数据表创建失败,失败信息:',e)
- 创建数据表的语句中需要先判断数据表是否存在,如果存在,抛出异常;
- 创建表的时候,要创建主键id,并设置PK属性和自增属性;
- 创建表的方法,要添加捕捉异常的方法,防止程序崩溃.
5.创建爬虫类–>创建获取页面响应方法
def get_career_info(self,url):
response = requests.get(url=url,headers=self.headers,timeout=5).json()
self.parse_career_info(response)
响应的数据是JSON数据,必须执行.json()方法,获取json格式的数据.
6.创建爬虫类–>创建解析数据方法
def parse_career_info(self,response):
c_list = response['Data']['Posts'] # 列表嵌套字典
work_id = 0
for work_info in c_list:
work_name = work_info['RecruitPostName']
country_name = work_info['CountryName']
city_name = work_info['LocationName']
category_name = work_info['CategoryName']
responsibility = work_info['Responsibility']
update_time = work_info['LastUpdateTime']
self.save_career_info(work_name,country_name,city_name,category_name,responsibility,update_time)
1. 分析响应的json数据格式,并用字典取值的方式获取数据列表;
2. 设置主键的初始化值=0;
3. 解析数据.
7.创建爬虫类–>将数据保存进数据库
def save_career_info(self,*args):
sql = """
insert into tencent_career_table(work_name,country_name,city_name,category_name,responsibility,update_time)
values(%s, %s, %s, %s, %s, %s)
"""
try:
self.cursor.execute(sql,args)
self.db.commit()
print('数据插入成功!')
except Exception as e:
print('数据录入失败,失败信息:',e)
self.db.rollback()
1. 执行插入语句时,要执行数据提交操作;
2. 数据插入失败时,要执行回滚操作;
3. 方法接收参数的格式.
8.创建主程序
def main(self):
self.create_table()
for page in range(1,32):
url = self.url.format(page)
self.get_career_info(url)
print('第{}页数据抓取完毕'.format(page))
time.sleep(random.randint(2,3))
用time模块控制数据抓取的速度