代码运行出来之后再读取表格,会出现一堆乱码,导致我不能制作关系图对数据进行分析。
import requests
import csv
import time
from selenium import webdriver
import matplotlib.pyplot as plt
# 数据写入模块
def csv_writer(file_name, item):
with open(file_name, 'a', encoding='utf-8', newline='') as fp:
writer = csv.writer(fp)
try:
writer.writerow(item)
except:
print('写入失败')
# 数据爬取模块
def spider():
# 使用webdriver打开头条首页
driver.get('https://www.zhipin.com/job_detail/?query=&city=100010000&industry=&position=')
# 定义url前缀
prefix = 'https://www.zhipin.com'
time.sleep(3)
# 定位搜索框
search_box = driver.find_element_by_xpath('//*[@id="filter-box"]/div/div[1]/div[1]/form/div[1]/p/input')
#输入搜索关键字
search_box.send_keys('数据分析师')
# 定位提交按钮
submit = driver.find_element_by_xpath('//*[@id="filter-box"]/div/div[1]/div[1]/form/button')
# 点击提交按钮
submit.click()
time.sleep(3)
# 循环提取出每页的书籍具体内容,设置翻页10次
for i in range( 1,10 ):
# 定位到每本书籍的链接元素
# book_items = driver.find_elements_by_xpath('//*[@id="main"]/div/div[3]/ul/li/div/div[1]/div[1]/div/div[1]/span[1]/a')
book_text = driver.find_elements_by_xpath('//*[@id="main"]/div/div[2]/ul/li/div/div[1]/div[1]/div')
# 循环处理a元素下的各个元素
for book in book_text:
# 提取a元素中的href属性,并和前缀一起构成每本书的详情页的url
money = book.find_element_by_xpath('div[2]/span').text
book_url = book.find_element_by_xpath('div[1]/span[1]/a')
url = prefix + book_url.get_attribute('href')
education = book.find_element_by_xpath('div[2]/p').text
place = book.find_element_by_xpath('div[1]/span[2]/span').text
item = (url,place,education,money)
# 将数据项写入csv文件
csv_writer('Boss.csv', item)
# print(item)
# 防止到最后一页没有相关元素,加入异常处理
try:
# 定位到下一页的元素
next_button = driver.find_element_by_xpath('//*[@id="main"]/div/div[@class="job-list"]/div[@class="page"]/a[@class="next"]')
# 点击下一页按钮
next_button.click()
except:
#如果出现异常,提示到最后一页
print('已经到最后一页')
time.sleep(5)
if __name__ == '__main__':
# 初始化webdriver
driver = webdriver.Chrome('chromedriver.exe')
spider()