Python基于requests庫爬取網(wǎng)站信息
requests庫是一個(gè)簡(jiǎn)介且簡(jiǎn)單的處理HTTP請(qǐng)求的第三方庫
get()是獲取網(wǎng)頁最常用的方式,其基本使用方式如下
使用requests庫獲取HTML頁面并將其轉(zhuǎn)換成字符串后,需要進(jìn)一步解析HTML頁面格式,這里我們常用的就是beautifulsoup4庫,用于解析和處理HTML和XML
下面這段代碼便是爬取百度的信息并簡(jiǎn)單輸出百度的界面信息
import requestsfrom bs4 import BeautifulSoupr=requests.get(’http://www.baidu.com’)r.encoding=Noneresult=r.textbs=BeautifulSoup(result,’html.parser’)print(bs.title)print(bs.title.text)
import requestsfrom bs4 import BeautifulSoup#用來解決亂碼現(xiàn)象,所以編寫爬取信息的代碼最好帶上(輸出出現(xiàn)亂碼或者UnicodeEncodeError:’gbk’codec can’t encode character) import io import syssys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding=’gb18030’)#用來防止反爬取,可以了解一下headers={'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.6)','Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Accept-Language' : 'en-us','Connection' : 'keep-alive','Accept-Charset' : 'GB2312,utf-8;q=0.7,*;q=0.7'}#獲取51job網(wǎng)站的基本信息r=requests.get(’https://search.51job.com/list/000000,000000,0000,00,9,99,python,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=’)r.encoding=r.apparent_encodingresult=r.textbs=BeautifulSoup(result,’html.parser’)print(bs.prettify())u1=bs.find_all(’u1’,attrs={’class’:’item_con_list’}) #這部分代碼便是我們爬取的目標(biāo),51job網(wǎng)站上關(guān)于python職業(yè)的薪資print(len(u1))li=bs.find_all(’span’,attrs={’class’:’t4’})for l in li: print(l.text)
上面這段代碼便是爬取51job網(wǎng)站上的與python相關(guān)職業(yè)的薪資
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. CSS hack用法案例詳解2. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法3. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析4. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明5. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向6. Ajax實(shí)現(xiàn)表格中信息不刷新頁面進(jìn)行更新數(shù)據(jù)7. PHP設(shè)計(jì)模式中工廠模式深入詳解8. 解決AJAX返回狀態(tài)200沒有調(diào)用success的問題9. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法10. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過程(親測(cè)可用)
