python網路資料擷取(伴奏曲)

來源:互聯網
上載者:User

標籤:執行   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網路資料擷取(伴奏曲)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.