智能決策上手系列教程索引
這是一個簡單的單頁面數(shù)據(jù)抓取案例袍辞,但也有些值得注意的坑浆兰。這里快速解釋一下代碼。
抓取的是51job網(wǎng)站盖桥,搜索“人工智能”然后得到的招聘職位基本信息灾螃,職位名、公司名揩徊、薪資等等腰鬼。
image.png
數(shù)據(jù)直接就在【右鍵-查看源代碼】的網(wǎng)頁源代碼里,也可以【右鍵-檢查】從Elements元素面板看到:
image.png
我們注意到職位列表都在class='dw_table'
的元素下面塑荒,但是第一個class='el title'
的是表頭熄赡,不應(yīng)該包含,雖然它下面也有t1,t2,t3
但是它的class='t1'
是個<span>
齿税,而正常的職位的t1
是個<p>
下面是主要代碼:
from bs4 import BeautifulSoup
import requests
import time
headers = {
'User-Agent': 'Mozilla/5.0'
}
url='https://search.51job.com/list/070300,000000,0000,00,9,99,%25E4%25BA%25BA%25E5%25B7%25A5%25E6%2599%25BA%25E8%2583%25BD,2,1.html?lang=c&stype=&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&providesalary=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare='
html= requests.get(url,headers=headers)
html=html.text.encode('ISO-8859-1').decode('gbk') ##注意這個坑彼硫!
soup=BeautifulSoup(html, 'html.parser')
for item in soup.find('div','dw_table').find_all('div','el'):
shuchu=[]
if item.find('p','t1'):
title=item.find('p','t1').find('a')['title']
company=item.find('span','t2').string #爬公司名稱
address=item.find('span','t3').string #爬地址
xinzi = item.find('span', 't4').string #爬薪資
date=item.find('span','t5').string #爬日期
shuchu.append(str(title))
shuchu.append(str(company))
shuchu.append(str(address))
shuchu.append(str(xinzi))
shuchu.append(str(date))
print('\t'.join(shuchu))
time.sleep(1)
有幾個坑需要注意:
-
html=html.text.encode('ISO-8859-1').decode('gbk')
沒有這句中文就會亂碼。因?yàn)槿绻W(wǎng)頁里沒有說明自己是什么編碼,Requests模塊就會把它當(dāng)做'uft-8'
編碼模式處理拧篮,而偏巧51job的網(wǎng)頁就沒有說明自己的編碼格式词渤,那就會使用網(wǎng)頁默認(rèn)的'ISO-8859-1'
編碼,這就矛盾了串绩,所以要強(qiáng)制重新編碼encode
然后再解碼decode
缺虐,這里使用gbk
確保中文正常顯示。 - 上面代碼用
if item.find('p','t1'):
排除掉了第一行表頭,參照上面的網(wǎng)頁截圖礁凡。 -
shuchu.append(str(title))
這里都加了str(...)
是防止有些時候公司名高氮、薪資、地址可能有空的顷牌,空的計(jì)算機(jī)會認(rèn)為是None
剪芍,我們用str(None)
就是'None'
,變成了一個字符串,不再是空了窟蓝。因?yàn)楹竺娴?code>'\t'.join(shuchu)中shuchu
列表里面如果有空就會出錯罪裹。
最終輸出的結(jié)果大致是:
image.png
智能決策上手系列教程索引
每個人的智能決策新時代
如果您發(fā)現(xiàn)文章錯誤,請不吝留言指正疗锐;
如果您覺得有用坊谁,請點(diǎn)喜歡;
如果您覺得很有用滑臊,歡迎轉(zhuǎn)載~
END