农民代表
- 积分
- 5099
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-7-11
- 最后登录
- 1970-1-1
|
web scraping careerbuilder- # -*- coding: utf-8 -*-
- import sys
- from urllib.request import urlopen
- from urllib.error import HTTPError
- import re
- import datetime
- import string
- from bs4 import BeautifulSoup
- import pymysql
- import nltk
- from nltk.corpus import stopwords. From 1point 3acres bbs
- from time import sleep # To prevent overwhelming the server ..
- . 1point 3acres
- date_today = datetime.date.today()
- stop_words = set(stopwords.words('english'))
- stop_words.update(set(string.punctuation))
- # Open database connection
- db = pymysql.connect("localhost", user = "testuser", passwd = "******",
- db="jobs", charset = 'utf8')
- # prepare a cursor object using cursor() method.--
- cursor = db.cursor()
- # execute SQL query using execute() method.
- #cursor.execute('''DROP TABLE IF EXISTS careerBuilder'''). 1point3acres
- cursor.execute (''' CREATE TABLE IF NOT EXISTS careerBuilder
- (id VARCHAR(50) NOT NULL, Company VARCHAR(150), Title VARCHAR(150), . Χ
- Location VARCHAR(150), Contents VARCHAR(3000),
- Industry VARCHAR(150), Category VARCHAR(150),
- Link VARCHAR(200), Salary VARCHAR(50), Created DATE,
- PRIMARY KEY(id)) ''')
- cursor.execute(''' SELECT id FROM careerBuilder ''')
- data = cursor.fetchall()
- jobid_visited = set([d[0] for d in data]).1point3acres
- ds_url = "https://www.careerbuilder.com/jobs-data-scientist"
- sort_by = "date_desc"
- page = 1-baidu 1point3acres
- url = "%s?page_number=%d&sort=%s" % (ds_url, page, sort_by)
- try:
- html = urlopen(url)
- except HTTPError as e:. Waral dи,
- print(e)
- sys.exit()
- soup = BeautifulSoup(html.read(), "lxml")
- num_pages = soup.find('span', attrs = {'class':'page-count'}).get_text(). Χ
- num_pages = int(re.findall(r'\d+', num_pages)[1])
- .google и
- base_url = "https://www.careerbuilder.com"
- #for page in range(1, num_pages + 1):
- for page in range(1, num_pages + 1):
- print('start page: ', page). 1point3acres.com
- url = "%s?page_number=%d&sort=%s" % (ds_url, page, sort_by)
- try:
- html = urlopen(url)
- except HTTPError as e:
- print(page, e)
- break
- soup = BeautifulSoup(html.read(), "lxml")
- jobs = soup.findAll('h2', attrs={'class':'job-title'}). From 1point 3acres bbs
- for job in jobs:
- # retriev job id
- job_did = job.a.get('data-job-did')
- if job_did in jobid_visited:
- continue.1point3acres
-
- job_link = base_url + job.a.get('href')
- try:
- job_soup = BeautifulSoup(urlopen(job_link).read(), "lxml")
- except Exception as e:
- print(page, job_did, e). .и
- continue
-
- job_detail = job_soup.find('div', attrs={'class':'card with-padding'}). .и
- title = job_detail.h1.get_text().strip()
- company_location = job_detail.h2.get_text().strip().split('\n')
- if len(company_location) == 1:
- location = company_location[0]
- elif len(company_location) == 3:
- company, location = company_location[0], company_location[2]. 1point 3acres
-
- # retriev job posted date
- begin_date = job_detail.h3.get_text().strip()
- begin_date = re.findall('(\d+) day', begin_date)
- if len(begin_date) == 0 :. 1point 3acres
- time_delta = 0
- else :. 1point 3acres
- time_delta = int(begin_date[0])
-
- begin_date = date_today - datetime.timedelta(days=time_delta)
- begin_date = begin_date.strftime("%y/%m/%d")
-
- # retriev job category. Waral dи,
- snapshot = job_detail.find('div', attrs={'class':'job-facts item'})
-
- job_industry = snapshot.find('div', id='job-industry')
- if job_industry:
- job_industry = job_industry.get_text().strip(). 1point 3 acres
-
- job_category = snapshot.find('div', id='job-categories')
- if job_category:
- job_category = job_category.get_text().strip(). 1point 3acres
-
- # find anually salary if available. 1point3acres
- salary = ''. check 1point3acres for more.
- for line in snapshot.get_text().splitlines():
- salary_entry = re.findall(r'^(\$.*)/Year
- -baidu 1point3acres
- , line)
- if len(salary_entry) == 1:
- salary = salary_entry[0].strip()
-
- job_id = job_detail.find('div', class_='small-12 columns job-id')
- if job_id:
- job_id = job_id.get_text().strip().split('\n')[1]
-
- # get job description and requirements
- job_item = job_detail.find('div', class_='small-12 columns item')
- text = job_item.get_text()
- # break into lines ..
- lines = (line.strip() for line in text.splitlines())
- # break multi-headlines into a line each
- chunks = (phrase.strip() for line in lines
- for phrase in line.split(" "))
-
- text = ' '.join(chunk for chunk in chunks if chunk)
- text = re.sub(r"[\'\-\/&]", r' ', text)
- words = nltk.tokenize.word_tokenize(text.lower()). ----
- words = [w for w in words if (not w in stop_words)]
- word_set = set(words)
- . 1point 3acres
- text = ' '.join(word_set). From 1point 3acres bbs
- if len(text) > 3000:. From 1point 3acres bbs
- text = text[:3000]
-
- company = re.sub(r'[\'\"]', r' ', company)
- location = re.sub(r'[\'\"]', r' ', location)
- title = re.sub(r'[\'\"]', r' ', title). Waral dи,
-
- if len(company) > 150:
- company = company[:150].1point3acres
-
- if len(title) > 150:
- title = title[:150]
-
- if len(location) > 150:. check 1point3acres for more.
- location = location[:150]
-
- # print(job_did, title, company, location, salary, begin_date, . Waral dи,
- # job_industry, job_category, job_link, text)
- # print("------------------------------------------")
-
- sql = '''INSERT INTO careerBuilder
- (id, Company, Title, Location, Contents, Industry,
- Category, Link, Salary, Created)
- VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', . 1point3acres
- '%s', '%s', STR_TO_DATE('%s', '%%y/%%m/%%d'))''' %\.
- (job_did, company, title, location, text,
- job_industry, job_category,
- job_link, salary, begin_date)
- try:
- cursor.execute(sql).1point3acres
- cursor.connection.commit()
- except Exception as e:. 1point 3 acres
- print(job_id, e). Χ
- break
-
- sleep(1)
- # Fetch a single row using fetchone() method.
- cursor.execute(''' SELECT * FROM careerBuilder ''')
- data = cursor.fetchone(). Χ
- print (data) -baidu 1point3acres
-
- # disconnect from server
- cursor.close()
- db.close()
. Waral dи,
复制代码 |
|