最近學習了一點爬蟲,就想著能不能通過企業微信的機器人發送一些圖片到微信群中,企業微信機器人說到底就是一個webhook地址,你也可以看成一個URL,而利用企業微信機器人發送圖片實則就是向服務器發送post請求,再將回應資料發送到webhook地址,以下是我爬取 彼岸圖網(http://pic.netbian.com)的python爬蟲代碼,使用的是強大的requests庫(scrapy框架還不太會用,就不用了)
import requests
from bs4 import BeautifulSoup
import os,re,time,hashlib,base64
head = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
}
start_urls = [] #定義一個url串列
for i in range(1,1000):
if(i==1):
url = 'http://pic.netbian.com/index.html' #判斷是否為首頁,并加入url串列中
start_urls.append(url)
else:
url = 'http://pic.netbian.com/index_'+str(i)+'.html' #判斷是否為非首頁,并加入url串列中
start_urls.append(url)
i = 1 #為了將圖片每二十張放入到不同的檔案夾
url1='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx' #自己的webhoook地址
for url in start_urls: #將url串列url依次取出
response = requests.get(url) #向服務器發出get請求,獲得回應
response.encoding='gbk' #設定回應的編碼格式為GBK
html = response.text #獲得相應的文本資訊
soup = BeautifulSoup(html,'lxml') #通過beautifulsoup庫中的lxml HTML 決議器提取資料
result = soup.find('ul',class_="clearfix").find_all('img') #找到<img>標簽
root = 'D:/page/SpiderImgs/imgs-'+str((i//20)+1)+'/' #拼接保存的路徑 根據自己要保存的路徑替換
for img in result:
path = root + img['src'].split('/')[-1] #獲取圖片資源名稱(http://pic.netbian.com/uploads/allimg/190824/212516-1566653116f355.jpg中的212516-1566653116f355.jpg)并拼接保存路徑
url = 'http://pic.netbian.com'+img['src'] #拼接圖片的url
r = requests.get(url, headers=head) #發送get請求圖片資源
if not os.path.exists(root): #判斷檔案夾是否存在
os.makedirs(root) #創建新的檔案夾
else:
with open (path,'wb+') as f: #創建一個檔案以二進制寫
f.write(r.content) #將請求服務器圖片資源的回應結果寫進檔案中
f.close()
print("圖片 "+str(i)+".jpg 保存成功")
try:
with open(path,'rb') as f: #以讀二進制的方式打開檔案
base64_data = base64.b64encode(f.read()).decode() #獲取base64編碼
file = open(path,'rb')
md = hashlib.md5()
md.update(file.read())
res1 = md.hexdigest() #獲取圖片內容的md5值
data = {
"msgtype" : 'image',
"image":{
"base64":base64_data,
"md5":res1
}
} #JSON資料格式
t = requests.post(url1, headers=head, json=data) #發送post請求
except:
print("例外")
print('\n')
i = i + 1 #檔案夾名稱加一
time.sleep(3) #讓程式睡3秒
以上代碼有任何問題或不懂可在評論區留言,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/226870.html
標籤:python
