python實現(xiàn)網(wǎng)絡爬蟲的方法:1、使用request庫中的get方法,請求url的網(wǎng)頁內(nèi)容;2、【find()】和【find_all()】方法可以遍歷這個html文件,提取指定信息。
python實現(xiàn)網(wǎng)絡爬蟲的方法:
第一步:爬取
使用request庫中的get方法,請求url的網(wǎng)頁內(nèi)容
編寫代碼[root@localhost demo]# touch demo.py
[root@localhost demo]# vim demo.py#web爬蟲學習 -- 分析
#獲取頁面信息
#輸入:url
#處理:request庫函數(shù)獲取頁面信息,并將網(wǎng)頁內(nèi)容轉(zhuǎn)換成為人能看懂的編碼格式
#輸出:爬取到的內(nèi)容
import requests
def getHTMLText(url):
try:
r = requests.get( url, timeout=30 )
r.raise_for_status() #如果狀態(tài)碼不是200,產(chǎn)生異常
r.encoding = 'utf-8' #字符編碼格式改成 utf-8
return r.text
except:
#異常處理
return " error "
url = "http://www.baidu.com"
print( getHTMLText(url) )[root@localhost demo]# python3 demo.py
第二步:分析
使用bs4庫中BeautifulSoup類,生成一個對象。find()和find_all()方法可以遍歷這個html文件,提取指定信息。
編寫代碼[root@localhost demo]# touch demo1.py
[root@localhost demo]# vim demo1.py
#web爬蟲學習 -- 分析
#獲取頁面信息
#輸入:url
#處理:request庫獲取頁面信息,并從爬取到的內(nèi)容中提取關(guān)鍵信息
#輸出:打印輸出提取到的關(guān)鍵信息
import requests
from bs4 import BeautifulSoup
import re
def getHTMLText(url):
try:
r = requests.get( url, timeout=30 )
r.raise_for_status() #如果狀態(tài)碼不是200,產(chǎn)生異常
r.encoding = 'utf-8' #字符編碼格式改成 utf-8
return r.text
except:
#異常處理
return " error "
def findHTMLText(text):
soup = BeautifulSoup( text, "html.parser" ) #返回BeautifulSoup對象
return soup.find_all(string=re.compile( '百度' )) #結(jié)合正則表達式,實現(xiàn)字符串片段匹配
url = "http://www.baidu.com"
text = getHTMLText(url) #獲取html文本內(nèi)容
res = findHTMLText(text) #匹配結(jié)果
print(res) #打印輸出[root@localhost demo]# python3 demo1.py文章來源:http://www.zghlxwxcb.cn/news/detail-809415.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-809415.html
到了這里,關(guān)于python實現(xiàn)網(wǎng)絡爬蟲代碼_python如何實現(xiàn)網(wǎng)絡爬蟲的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!