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设计】。

相关文章

matplotlib作图添加表格实例代码

matplotlib作图添加表格实例代码

本文所示代码主要是通过Python+matplotlib实现作图,并且在图中添加表格的功能,具体如下。 代码 import matplotlib.pyplot as plt impo...

Python中Flask-RESTful编写API接口(小白入门)

Python中Flask-RESTful编写API接口(小白入门)

1.API接口:hello world 案例 from flask import Flask from flask_restful import Api, Resource app...

使用python绘制常用的图表

使用python绘制常用的图表

本文介绍如果使用python汇总常用的图表,与Excel的点选操作相比,用python绘制图表显得比较比较繁琐,尤其提现在对原始数据的处理上。但两者在绘制图表过程中的思路大致相同,Exc...

python处理二进制数据的方法

本文实例讲述了python处理二进制数据的方法。分享给大家供大家参考。具体如下: #!/usr/env/env python #-*- coding: cp936 -*- '''...

Empty test suite.(PyCharm程序运行错误的解决方法)

Empty test suite.(PyCharm程序运行错误的解决方法)

运行程序test4_4.py时报错,Empty test suite. 查找资料发现原因: 默认情况下,PyCharm将检查以test开头的文件,它们是unittest.TestCas...