Python3.6 爬蟲初體驗--urllib、beautifulsoup(一)
阿新 • • 發佈:2019-01-10
經常查詢IP地址相關,有時目標太多需要批量操作,於是想到python爬蟲,批量查詢、模式輸出,廢話不多說,程式碼奉上!
p.s. 涉及到的兩個主要模組–urllib、BeautifulSoup
p.s. 本文主要介紹以上兩模組使用,故涉及到的IP查詢網站就用www.URL.com代替了
import urllib.request #python3.6中url請求模組只能用這種方式匯入,其他方式親測失敗。。。
from bs4 import BeautifulSoup #同上,python3.6中的beautifulsoup匯入方式,其他方式親測失敗。。。
import re
import time
with open('ipresult.txt','w') as out: #建立並開啟結果儲存文字
with open('ipurl.txt','r') as list: #開啟已經存在的需查詢域名文字
for data in list: #以下為打印出所查詢域名以及分割線
print('-'*50,file=out)
print("網站域名",data,file=out)
url="http://www.URL.com/" #查詢請求網址
full_url=url+data #構造每個域名的查詢url
data=urllib.request.urlopen(full_url).read() #發起請求並讀取回應
data=data.decode('UTF-8')
soup = BeautifulSoup(data,"html.parser") #使用beautifulsoup分析迴應
#time.sleep(20)
#以下為抓取回的頁面中涉及ip地址及物理位置的html內容,根據其中的標籤及class提取出想要的內容
""" <p class="WhwtdWrap bg-blue08 col-gray03">
<span class="Whwtdhalf w15-0">域名/IP</span>
<span class="Whwtdhalf w15-0">獲取的IP地址</span>
<span class="Whwtdhalf w15-0">數字地址</span>
<span class="Whwtdhalf w50-0">IP的物理位置</span>
</p>
<p class="WhwtdWrap bor-b1s col-gray03">
<span class="Whwtdhalf w15-0">www.hXXXXX.com</span>
<span class="Whwtdhalf w15-0">45.120.XX.XX</span>
<span class="Whwtdhalf w15-0">7628XXXXXX</span>
<span class="Whwtdhalf w50-0">IANA 保留地址</span>
</p>
"""
for link in soup.find_all('span'): #此for迴圈為通過匹配html標籤“span”,大體定位ip地址
text_span = link.get_text()
ip_finder = re.compile(r'(\d{1,3}\.){3}\d{1,3}') #此處正則匹配ip地址
ip = ip_finder.search(text_span)
if ip :
print("IP地址為:",ip.group(),file=out) #正則匯出ip地址內容
lo_finder = link.get('class') #使用lo_finder代表從span標籤中提取出全部class標籤
lo_class = ['Whwtdhalf', 'w50-0'] #觀察以上html發現標記物理位置的class為class="Whwtdhalf w50-0",與其他class明顯不同,故作if判斷進一步提取,但是此時還有(IP的物理位置)這一文字內容也是此class
if lo_finder == lo_class:
lo_text = link.get_text()
#print(lo_text)
if lo_text != 'IP的物理位置': #排除相同class標籤的另一文字內容(IP的物理位置),即可提取出想要的物理位置
print("伺服器位於",lo_text,file=out)
#lo_patten = re.compile(r'')
#lo = lo_patten.match(lo_text)
#if lo :
# print("伺服器位於",lo.group(),file=out)
#print(lo,file=out)
print('-'*50,file=out)
print("執行結束")
輸出結果示例如下(為保護隱私有關資訊用”X”代替):
--------------------------------------------------
網站域名 www.hXXXXX.com
IP地址為: 103.56.XX.XX
伺服器位於 亞太地區
--------------------------------------------------
網站域名 www.hXXXXX.com
IP地址為: 45.127.XX.XX
伺服器位於 IANA 保留地址
--------------------------------------------------
網站域名 www.hXXXXXX.com
IP地址為: 124.248.XX.XX
伺服器位於 香港 XXX(SunnXXXXXX)資料中心(XXXXXXX)
--------------------------------------------------
網站域名 www.hXXXXXXX.com
IP地址為: 42.123.XX.XX
伺服器位於 貴州省貴陽市
--------------------------------------------------
網站域名 www.hXXXXXX.com
IP地址為: 119.28.XX.XX
伺服器位於 香港 北京XXXXXXX有限責任公司