python之簡單爬取一個網站信息


requests庫是一個簡介且簡單的處理HTTP請求的第三方庫

get()是獲取網頁最常用的方式,其基本使用方式如下

使用requests庫獲取HTML頁面並將其轉換成字符串后,需要進一步解析HTML頁面格式,這里我們常用的就是beautifulsoup4庫,用於解析和處理HTML和XML

下面這段代碼便是爬取百度的信息並簡單輸出百度的界面信息

import requests
from bs4 import BeautifulSoup

r=requests.get('http://www.baidu.com')
r.encoding=None
result=r.text
bs=BeautifulSoup(result,'html.parser')
print(bs.title)
print(bs.title.text)

 

import requests
from bs4 import BeautifulSoup

#用來解決亂碼現象,所以編寫爬取信息的代碼最好帶上(輸出出現亂碼或者UnicodeEncodeError:'gbk'codec can't encode character)  
import io      
import sys
sys.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網站的基本信息 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&degreefrom=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_encoding result=r.text bs=BeautifulSoup(result,'html.parser') print(bs.prettify()) u1=bs.find_all('u1',attrs={'class':'item_con_list'}) #這部分代碼便是我們爬取的目標,51job網站上關於python職業的薪資 print(len(u1)) li=bs.find_all('span',attrs={'class':'t4'}) for l in li: print(l.text)

上面這段代碼便是爬取51job網站上的與python相關職業的薪資

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2024 CODEPRJ.COM