楼主: 奇点ML
2360 3

[程序分享] python 网络爬虫代码分享 [推广有奖]

  • 0关注
  • 0粉丝

小学生

42%

还不是VIP/贵宾

-

威望
0
论坛币
25 个
通用积分
0
学术水平
0 点
热心指数
0 点
信用等级
0 点
经验
243 点
帖子
4
精华
0
在线时间
3 小时
注册时间
2017-7-17
最后登录
2017-7-24

楼主
奇点ML 发表于 2017-7-21 13:40:12 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
Python 网络爬虫代码分享,希望大家多多交流指正!
网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。另外一些不常使用的名字还有蚂蚁、自动索引、模拟程序或者蠕虫
  1. from pprint import pprint
  2. import csv
  3. from collections import Counter
  4. import requests
  5. from bs4 import BeautifulSoup
  6. import jieba
  7. import matplotlib.pyplot as plt
  8. from wordcloud import WordCloud

  9. class JobSpider():

  10.     def __init__(self):
  11.         self.company = []
  12.         self.text = ""
  13.         self.headers = {'X-Requested-With': 'XMLHttpRequest',
  14.                         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
  15.                                       'Chrome/56.0.2924.87 Safari/537.36'}

  16.     def job_spider(self):
  17.         """ 爬虫入口 """
  18.         url = "http://search.51job.com/list/010000%252C020000%252C030200%252C040000,000000,0000,00,9,99,Python,2,{}.html?" \
  19.               "lang=c&stype=1&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&lonlat=0%2C0" \
  20.               "&radius=-1&ord_field=0&confirmdate=9&fromType=1&dibiaoid=0&address=&line=&specialarea=00&from=&welfare="
  21.         urls = [url.format(p) for p in range(1, 14)]
  22.         for url in urls:
  23.             r = requests.get(url, headers=self.headers).content.decode('gbk')
  24.             bs = BeautifulSoup(r, 'lxml').find("div", class_="dw_table").find_all("div", class_="el")
  25.             for b in bs:
  26.                 try:
  27.                     href, post = b.find('a')['href'], b.find('a')['title']
  28.                     locate = b.find('span', class_='t3').text
  29.                     salary = b.find('span', class_='t4').text
  30.                     d = {'href':href, 'post':post, 'locate':locate, 'salary':salary}
  31.                     self.company.append(d)
  32.                 except Exception:
  33.                     pass

  34.     def post_require(self):
  35.         """ 爬取职位描述 """
  36.         for c in self.company:
  37.             r = requests.get(c.get('href'), headers=self.headers).content.decode('gbk')
  38.             bs = BeautifulSoup(r, 'lxml').find('div', class_="bmsg job_msg inbox").text
  39.             s = bs.replace("举报", "").replace("分享", "").replace("\t", "").strip()
  40.             self.text += s
  41.         # print(self.text)
  42.         with open(r".\data\post_require.txt", "w+", encoding="utf-8") as f:
  43.             f.write(self.text)

  44.     def post_desc_counter(self):
  45.         """ 职位描述统计 """
  46.         # import thulac
  47.         post = open(r".\data\post_require.txt", "r", encoding="utf-8").read()
  48.         # 使用 thulac 分词
  49.         # thu = thulac.thulac(seg_only=True)
  50.         # thu.cut(post, text=True)

  51.         # 使用 jieba 分词
  52.         jieba.load_userdict(r".\data\user_dict.txt")
  53.         seg_list = jieba.cut(post, cut_all=False)
  54.         counter = dict()
  55.         for seg in seg_list:
  56.             counter[seg] = counter.get(seg, 1) + 1
  57.         counter_sort = sorted(counter.items(), key=lambda value: value[1], reverse=True)
  58.         pprint(counter_sort)
  59.         with open(r".\data\post_pre_desc_counter.csv", "w+", encoding="utf-8") as f:
  60.             f_csv = csv.writer(f)
  61.             f_csv.writerows(counter_sort)

  62.     def post_counter(self):
  63.         """ 职位统计 """
  64.         lst = [c.get('post') for c in self.company]
  65.         counter = Counter(lst)
  66.         counter_most = counter.most_common()
  67.         pprint(counter_most)
  68.         with open(r".\data\post_pre_counter.csv", "w+", encoding="utf-8") as f:
  69.             f_csv = csv.writer(f)
  70.             f_csv.writerows(counter_most)

  71.     def post_salary_locate(self):
  72.         """ 招聘大概信息,职位,薪酬以及工作地点 """
  73.         lst = []
  74.         for c in self.company:
  75.             lst.append((c.get('salary'), c.get('post'), c.get('locate')))
  76.         pprint(lst)
  77.         with open(r".\data\post_salary_locate.csv", "w+", encoding="utf-8") as f:
  78.             f_csv = csv.writer(f)
  79.             f_csv.writerows(lst)

  80.     def post_salary(self):
  81.         """ 薪酬统一处理 """
  82.         mouth = []
  83.         year = []
  84.         thouand = []
  85.         with open(r".\data\post_salary_locate.csv", "r", encoding="utf-8") as f:
  86.             f_csv = csv.reader(f)
  87.             for row in f_csv:
  88.                 if "万/月" in row[0]:
  89.                     mouth.append((row[0][:-3], row[2], row[1]))
  90.                 elif "万/年" in row[0]:
  91.                     year.append((row[0][:-3], row[2], row[1]))
  92.                 elif "千/月" in row[0]:
  93.                     thouand.append((row[0][:-3], row[2], row[1]))
  94.         # pprint(mouth)
  95.         calc = []
  96.         for m in mouth:
  97.             s = m[0].split("-")
  98.             calc.append((round((float(s[1]) - float(s[0])) * 0.4 + float(s[0]), 1), m[1], m[2]))
  99.         for y in year:
  100.             s = y[0].split("-")
  101.             calc.append((round(((float(s[1]) - float(s[0])) * 0.4 + float(s[0])) / 12, 1), y[1], y[2]))
  102.         for t in thouand:
  103.             s = t[0].split("-")
  104.             calc.append((round(((float(s[1]) - float(s[0])) * 0.4 + float(s[0])) / 10, 1), t[1], t[2]))
  105.         pprint(calc)
  106.         with open(r".\data\post_salary.csv", "w+", encoding="utf-8") as f:
  107.             f_csv = csv.writer(f)
  108.             f_csv.writerows(calc)

  109.     def post_salary_counter(self):
  110.         """ 薪酬统计 """
  111.         with open(r".\data\post_salary.csv", "r", encoding="utf-8") as f:
  112.             f_csv = csv.reader(f)
  113.             lst = [row[0] for row in f_csv]
  114.         counter = Counter(lst).most_common()
  115.         pprint(counter)
  116.         with open(r".\data\post_salary_counter1.csv", "w+", encoding="utf-8") as f:
  117.             f_csv = csv.writer(f)
  118.             f_csv.writerows(counter)

  119.     def world_cloud(self):
  120.         """ 生成词云 """
  121.         counter = {}
  122.         with open(r".\data\post_desc_counter.csv", "r", encoding="utf-8") as f:
  123.             f_csv = csv.reader(f)
  124.             for row in f_csv:
  125.                 counter[row[0]] = counter.get(row[0], int(row[1]))
  126.             pprint(counter)
  127.         wordcloud = WordCloud(font_path=r".\font\msyh.ttf",
  128.                               max_words=100, height=600, width=1200).generate_from_frequencies(counter)
  129.         plt.imshow(wordcloud)
  130.         plt.axis('off')
  131.         plt.show()
  132.         wordcloud.to_file('.\images\worldcloud.jpg')

  133.     def insert_into_db(self):
  134.         """ 插入数据到数据库
  135.             create table jobpost(
  136.                 j_salary float(3, 1),
  137.                 j_locate text,
  138.                 j_post text
  139.             );
  140.         """
  141.         import pymysql
  142.         conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="0303", db="chenx", charset="utf8")
  143.         cur = conn.cursor()
  144.         with open(r".\data\post_salary.csv", "r", encoding="utf-8") as f:
  145.             f_csv = csv.reader(f)
  146.             sql = "insert into jobpost(j_salary, j_locate, j_post) values(%s, %s, %s)"
  147.             for row in f_csv:
  148.                 value = (row[0], row[1], row[2])
  149.                 try:
  150.                     cur.execute(sql, value)
  151.                     conn.commit()
  152.                 except Exception as e:
  153.                     print(e)
  154.         cur.close()

  155. if __name__ == "__main__":
  156.     spider = JobSpider()
  157.     # spider.job_spider()
  158.     # spider.post_salary()
  159.     # spider.insert_into_db()
  160.     # spider.post_salary_counter()
  161.     # spider.post_counter()
  162.     # spider.world_cloud()
复制代码
大家可以在讨论区交流一下!

二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:Python 网络爬虫

已有 1 人评分经验 论坛币 收起 理由
残阳_等待 + 60 + 5 精彩帖子

总评分: 经验 + 60  论坛币 + 5   查看全部评分

沙发
奇点ML 发表于 2017-7-21 13:46:33
新手可以试着跑一下,高手可以给点意见!

藤椅
AI学咖 发表于 2017-7-21 13:48:12
作为伸手党,就不客气啦,先试着跑一下 Python 网络爬虫的代码,遇到问题还希望楼主多多指教,现在不会点爬虫感觉真的就 OUT 了!再次感谢分享!
已有 1 人评分经验 收起 理由
残阳_等待 + 5 精彩帖子

总评分: 经验 + 5   查看全部评分

板凳
訁商 发表于 2017-7-21 13:50:28
路过,最近在学习 Python,爬虫作为最容易实现的工具且最为实用的工具真的挺重要的,感谢楼主的分享,看书看教材看视频真的不如实际动手操作,遇到问题再找大牛老师解答!希望楼主不吝赐教!
已有 1 人评分经验 收起 理由
残阳_等待 + 5 精彩帖子

总评分: 经验 + 5   查看全部评分

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2025-12-29 00:07