標籤:執行 lib ref 輸出 wiki 資料 org 運行 連結
這裡是前章,我們做一下預備。之前太多事情沒能寫部落格~。。 (此部落格只適合python3x,python2x請自行更改代碼)
首先你要有bs4模組
windows下安裝:pip3 install bs4,如果你電腦有python2x和python3x的話,在python3x中安裝bs4請已管理員的身份運行cmd執行pip3 install bs4安裝bs4。
linux下安裝:sudo pip3 install bs4
還有urllib.request模組
windows下安裝:pip3 install urllib.request,如果你電腦有python2x和python3x的話,在python3x中安裝bs4請已管理員的身份運行cmd執行pip3 install urllib.request安裝urllib.request模組
例子1:擷取源碼
from urllib.request import urlopen
from bs4 import BeautifulSoup
html=urlopen("http://wikipedia.org")
dgc=BeautifulSoup(html)
print(dgc)
輸出圖如下:
這裡我忘記加自訂錯誤了,當然你也可以不加。保險起見還是加
例子二:匹配對應的標籤
from urllib.request import urlopen
from bs4 import BeautifulSoup
try:
html=urlopen("http://dlszx.dgjy.net/")
except EOFError as a:
print("404 ")
except:
print("404")
dgc=BeautifulSoup(html)
fbc=dgc.findAll("img",{"src":"uploadfile/201762105219962.jpg"})
print(fbc)
例子3:正則匹配所有對應的標籤
不會正則的請去學習
from urllib.request import urlopen
import re
from bs4 import BeautifulSoup
try:
html=urlopen("http://dlszx.dgjy.net/")
except EOFError as a:
print("404 ")
except:
print("404")
dgc=BeautifulSoup(html)
fbc=dgc.findAll("img",{"src":re.compile("img/.*?\.jpg")})
for inks in fbc:
print(inks)
注意事項!!!:不要拿findAll去搜尋引擎匹配,亂的你想死
搜尋引擎正則匹配要求很高:http:\/\/[a-zA-z].*?\[a-z]
例子4:
匹配網站所有的連結
from urllib.request import urlopen
import re
from bs4 import BeautifulSoup
try:
html=urlopen("http://wikipeda.org")
except EOFError as a:
print("EOFError")
except:
print("I dont EOFError")
gfc=BeautifulSoup(html)
for inks in gfc.findAll("a")
if ‘href‘ in inks.attrs:
print("inks.attrs["href"]")
現在的時間是
2017-8-13-13:38
python網路資料擷取(伴奏曲)