python 网页抓取信息

目标:从下面这个网页抓取前10页IP、端口、运营商、地址、最后检测时间并存入mysql数据库

代码:

import requests
import re
import pandas as pd
import pymysql
#导入需要使用到的模块
class huoqu():
    #读入数据
    def __init__(self):
        self.num=1
        for i in range(10):
            #获取网页信息
            response = requests.get('http://www.89ip.cn/index_%d.html'%i)
            self.HTML = response.text
            #print(HTML)
            #是一个字符串
            #提取信息
            self.ip = re.compile(r'<tr>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?</tr>',re.S)
            self.res = re.findall(self.ip,self.HTML)
            self.DButil(self.res)
    def DButil(self,res):
        #建立数据库连接
        self.db=pymysql.connect('localhost','root','root','python_an')
        #获取游标对象
        self.cursor = self.db.cursor()
        for ip_ in self.res:
            self.num+=1
            #插入数据语句
            query = """insert into catering_sale (num,IP,port,geographical,perators,final_detection) values (%s,%s,%s,%s,%s,%s)"""
       #去\t \n操作
       values = (self.num,ip_[0].replace('\n', '').replace('\t', ''),ip_[1].replace('\n', '').replace('\t', ''),ip_[2].replace('\n', '').replace('\t', ''),ip_[3].replace('\n', '').replace('\t', ''),ip_[4].replace('\n', '').replace('\t', '')) self.cursor.execute(query,values) #关闭游标,提交,关闭数据库连接 #如果没有这些关闭操作,执行后在数据库中查看不到数据 self.cursor.close() self.db.commit() self.db.close() if __name__=='__main__': huoqu=huoqu() huoqu.__init__
<tr>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?</tr>
对应源码:
</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>
  101.4.136.34 </td>
  <td>
  8080 </td>
  <td>
  北京市 </td>
  <td>
  教育网 </td>
  <td>
  2019/08/05 17:30:08 </td>
  </tr>
  <tr>
  <td>


数据库:

提醒:安装pymysql:python -m pip install pymysql

测试结果:

猜你喜欢

转载自www.cnblogs.com/abels0025/p/11304579.html