python爬虫爬取ip记录网站信息并存入数据库

时间:2021-10-17 19:48:43
 import requests
import re
import pymysql
#10页 仔细观察路由
db = pymysql.connect("localhost","root","root","testdb" )
cursor = db.cursor() for i in range(1,10):
url = 'http://*******8****'
url=url+'index_'+str(i)+'.html'
response = requests.get(url)
HTML = response.text
pattern= re.compile(r'(((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3})')
compile_1 = re.compile(r'\s+(\d{3,6})\s')
compile_2 = re.compile(r'\s+([\u4e00-\u9fa5]{1,9})\s?(?:省|*|内蒙古|市|县|区])')
# compile_4 = re.compile(r's+(\d{4}/\d{2}/\d{2}\s+\d{2}:\d{2}:\d{2})\s')
res2 = compile_2.findall(HTML)
res1 = compile_1.findall(HTML)
result = pattern.findall(HTML)
# res3 = compile_4.findall(HTML)
# print(res3,len(result))
for ip_ in result:
print(ip_[0])
sql = "INSERT INTO test (ip,port,place) VALUES ('%s','%s','%s')" %(ip_[0],res1[0],res2[0])
print(sql)
cursor.execute(sql)
db.close() # 使用cursor()方法获取操作游标