目的:獲取騰訊社招這個(gè)頁面的職位名稱及超鏈接 職位類別 人數(shù) 地點(diǎn)和發(fā)布時(shí)間
要求:使用bs4進(jìn)行解析,并把結(jié)果以json文件形式存儲(chǔ)
注意:如果直接把python列表沒有序列化為json數(shù)組,寫入到j(luò)son文件,會(huì)產(chǎn)生中文寫不進(jìn)去到文件,所以要序列化并進(jìn)行utf-8編碼后寫入文件。
# -*- coding:utf-8 -*- import requests from bs4 import BeautifulSoup as bs import json url = 'https://hr.tencent.com/position.php?' params = { 'start':'10' } headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' } # 獲取騰訊社招某個(gè)頁面的頁面源碼 html = requests.get(url, params = params, headers = headers).text # 創(chuàng)建soup對象,使用lxml解析器 soup = bs(html,'lxml') # 選取類名為odd和even的tr標(biāo)簽 result1 = soup.select('tr[class="odd"]') result2 = soup.select('tr[class="even"]') # 列表拼接 l = [1,2] + [3,4],則列表l為[1,2,3,4] result = result1 + result2 # 把數(shù)據(jù)存放在列表里面,列表的每個(gè)元素都為一個(gè)字典 l = [] data = {} for item in result: # 獲取標(biāo)簽的文本內(nèi)容 job = item.find_all('a')[0].get_text().encode('utf-8') category = item.find_all('td')[1].get_text().encode('utf-8') number = item.find_all('td')[2].get_text().encode('utf-8') address = item.find_all('td')[3].get_text().encode('utf-8') public_time = item.find_all('td')[4].get_text().encode('utf-8') # 獲取標(biāo)簽的屬性值 link = item.find_all('a')[0].attrs['href'] fulllink = ('https://hr.tencent.com/' + link).encode('utf-8') data['job'] = job data['category'] = category data['number'] = number data['address'] = address data['public_time'] = public_time data['fulllink'] = fulllink l.append(data) # 原來中文寫不到文件里面的報(bào)錯(cuò)原因,沒把python列表序列化為json數(shù)組 # with open('tencent.json','a') as f: # f.write(str(data) + '\n') # 方法1存儲(chǔ)數(shù)據(jù),上面字典的值不用先進(jìn)行utf-8編碼 # 把數(shù)據(jù)以json文件形式存儲(chǔ) # f = open('tencent.json','a') # 把python列表序轉(zhuǎn)化為json對象。本地操作常用的是load dump。網(wǎng)絡(luò)操作常用的loads dumps,而loads常用來把json格式轉(zhuǎn)化為python格式,dumps把python格式序列為json格式 # dictdata = json.dumps(l,ensure_ascii=False) # 把json對象寫入json文件 # f.write(dictdata.encode('utf-8')) # f.close() # 把數(shù)據(jù)存入tencent.json文件內(nèi) json.dump(l,open('tencent.json','a'),ensure_ascii=False)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
