目的:獲取騰訊社招這個頁面的職位名稱及超鏈接 職位類別 人數 地點和發布時間
要求:使用bs4進行解析,并把結果以json文件形式存儲
注意:如果直接把python列表沒有序列化為json數組,寫入到json文件,會產生中文寫不進去到文件,所以要序列化并進行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' } # 獲取騰訊社招某個頁面的頁面源碼 html = requests.get(url, params = params, headers = headers).text # 創建soup對象,使用lxml解析器 soup = bs(html,'lxml') # 選取類名為odd和even的tr標簽 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 # 把數據存放在列表里面,列表的每個元素都為一個字典 l = [] data = {} for item in result: # 獲取標簽的文本內容 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') # 獲取標簽的屬性值 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) # 原來中文寫不到文件里面的報錯原因,沒把python列表序列化為json數組 # with open('tencent.json','a') as f: # f.write(str(data) + '\n') # 方法1存儲數據,上面字典的值不用先進行utf-8編碼 # 把數據以json文件形式存儲 # f = open('tencent.json','a') # 把python列表序轉化為json對象。本地操作常用的是load dump。網絡操作常用的loads dumps,而loads常用來把json格式轉化為python格式,dumps把python格式序列為json格式 # dictdata = json.dumps(l,ensure_ascii=False) # 把json對象寫入json文件 # f.write(dictdata.encode('utf-8')) # f.close() # 把數據存入tencent.json文件內 json.dump(l,open('tencent.json','a'),ensure_ascii=False)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

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