python3判断url链接是否为404的方法

yipeiwu_com7年前Python基础

本文实例为大家分享了python3判断url链接是否为404的具体代码,供大家参考,具体内容如下

import pymysql
import threading
import time
import urllib
import requests
 
# 打开数据库连接
db = pymysql.connect("192.168.0.*", "username", "password", "databasename")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 查询语句
sql = "SELECT sku,url_6 FROM url_new where flag_6 is null and url_6<>'' "
  # 执行SQL语句
cursor.execute(sql)
  # 获取所有记录列表
results = cursor.fetchall()
num = 0
for row in results:
  sku = row[0]
  url = row[1]
  html = requests.head(url) # 用head方法去请求资源头
  re=html.status_code
  num = num + 1
  print(num,re)
  if re == 200:
    sql_2 = "UPDATE url_new SET flag_6 = 0 WHERE sku = '%s'" % sku
    try:
      # 执行SQL语句
      cursor.execute(sql_2)
      #print(cursor.rowcount)
    except Exception as e:
      print(e)
      conn.rollback()
  if re == 404:
    sql_3 = "UPDATE url_new SET flag_6 = 1 WHERE sku = '%s'" % sku
    try:
      # 执行SQL语句
      cursor.execute(sql_3)
      print(cursor.rowcount)
    except Exception as e:
      print(e)
      conn.rollback()
  db.commit()
db.close()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Django 1.10以上版本 url 配置注意事项详解

在改造旧版本django cms程序从 pyton2.7, django 1.8版本升到 python 3.5,django 1.11版本的时候,原以为会非常轻松,却不想在URL配置上就...

python绘制规则网络图形实例

我就废话不多说,直接上代码吧! #Copyright (c)2017, 东北大学软件学院学生 # All rightsreserved #文件名称:a.py # 作 者:孔云 #问...

Python中实现的RC4算法

闲暇之时,用Python实现了一下RC4算法 编码 UTF-8 class 方式 #/usr/bin/python #coding=utf-8 import sys,os,hash...

python 含子图的gif生成时内存溢出的方法

今天想用python做个demo,含两个子图的动态gif,代码如下: import matplotlib.pyplot as plt import imageio,os import...

有趣的python小程序分享

有趣的python小程序分享

python可以简单优美,也很有趣,下面是收集的例子: 1.一句话开始一个http的文件服务器: $ python -m SimpleHTTPServer Serving HTTP on...