1. 程式人生 > >python使用selenium自動化批量ip查詢

python使用selenium自動化批量ip查詢

功能

1:開啟網址,
2:在中間輸入ip地址,
3:點選查詢
4:進行螢幕截圖,並且用ip的名字進行儲存,例如127-0-0-1.jpg
5:儲存螢幕原始碼,並且用ip的名字進行儲存,同上
6:將原始碼中出現(*)的ip地址抽取抽取出來

程式碼

#-*- coding:utf-8 -*-
import unittest
import time
import re
from selenium import webdriver
from selenium.webdriver.common.keys import Keys



url = "http://www.ipip.net/ip.html"
driver = webdriver.Chrome() def get_data(ip): #開啟請求的url driver.get(url) assert "IPIP" in driver.title elem = driver.find_element_by_name("ip") #ip為搜尋框的名字 elem.send_keys(ip) #輸入內容 elem.send_keys(Keys.RETURN)#模擬點選回車 #driver.save_screenshot("1.png") page = driver.page_source.encode('utf-8'
) all_file_name = "/home/xuna/桌面/all_res/" + ip + ".txt" res_file_name = "/home/xuna/桌面/res/" + ip + ".txt" file = open(all_file_name,"w") file.write(page) print page.find("**") #返回值為 -1:不存在 if page.find("**") != -1: file = open(res_file_name,"w") file.write(page) file.close() if
__name__ == "__main__": """ get_data("123.1.1.1") get_data("1.1.1.1") """ file_path = "/home/xuna/桌面/selenium/res_url.txt" fout = open(file_path,"rb") n = 0 for ip in fout: try: if ip[0] >='1' and ip[0] <='9': #正則表示式提取ip,過濾空格,換行符 res = re.findall(r'\d+\.\d+\.\d+\.\d+',ip) print n,res[0] get_data(str(res[0])) n = n + 1 except: print n,"錯誤" pass

參考資料