PYTHON实现爬取boss直聘信息并添加注释,给出实例代码
时间: 2024-01-06 13:04:38 浏览: 26
好的,以下是一个基于Python的爬取boss直聘信息并添加注释的实例代码:
```python
import requests
from bs4 import BeautifulSoup
import csv
# 设置请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 定义爬取函数
def get_jobs(keyword, city):
# 构造请求URL
url = 'https://www.zhipin.com/job_detail/?query=' + keyword + '&city=' + city + '&industry=&position='
# 发送请求
response = requests.get(url, headers=headers)
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 获取职位信息
jobs = soup.find_all('div', class_='job-list')
# 新建CSV文件,写入职位信息
with open('jobs.csv', 'w', newline='', encoding='utf-8-sig') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['职位名称', '公司名称', '薪资', '城市', '经验要求', '学历要求', '公司福利'])
for job in jobs:
job_name = job.find('span', class_='job-title').text.strip()
company_name = job.find('div', class_='company-text').find('h3').text.strip()
salary = job.find('span', class_='red').text.strip()
city = job.find('span', class_='job-city').text.strip()
exp_edu = job.find('div', class_='job-desc').find_all('p')
experience = exp_edu[0].text.strip()
education = exp_edu[1].text.strip()
welfare = job.find('div', class_='tag-list').text.strip()
writer.writerow([job_name, company_name, salary, city, experience, education, welfare])
print('职位名称:', job_name)
print('公司名称:', company_name)
print('薪资:', salary)
print('城市:', city)
print('经验要求:', experience)
print('学历要求:', education)
print('公司福利:', welfare)
print('-' * 50)
# 测试爬取函数
get_jobs('Python', '北京')
```
这段代码使用了requests库和BeautifulSoup库来发送HTTP请求和解析HTML,通过构造请求URL来爬取boss直聘网站上的职位信息,然后将这些信息写入CSV文件,并在控制台输出职位名称、公司名称、薪资、城市、经验要求、学历要求和公司福利等信息,同时添加了注释来提高代码的可读性。