首页 > 数据库 >Python爬虫爬取html中div下的多个class标签并存入数据库

Python爬虫爬取html中div下的多个class标签并存入数据库

时间:2023-02-09 11:22:04浏览次数:33  
标签:cursor Python text 爬取 html date div data

使用python爬虫爬取html页面div中的多个class标签,获取后将数据存成列表,然后存入数据库

import mysql.connector
import pymysql
import requests
from bs4 import BeautifulSoup

# Connect to the database
conn = mysql.connector.connect(user='root', password='123456', host='127.0.0.1', database='listdb')
cursor = conn.cursor()

# Create table if not exists
cursor.execute('''CREATE TABLE IF NOT EXISTS data (
    id INT AUTO_INCREMENT PRIMARY KEY,
    date VARCHAR(255),
    text VARCHAR(255)
)''')
conn.commit()

# Sample data
url = "https://url/"
response = requests.get(url)
html_content = response.text

# 使用 BeautifulSoup 解析 HTML
soup = BeautifulSoup(html_content, "html.parser")

# 获取 div 元素下多个 class 的数据
data = []
for div in soup.find_all("div", class_=["post-meta", "post-title"]):
    content = div.text.strip()
    data.append(content)


# Iterate over the data
for i in range(0, len(data), 2):
    date = data[i]
    text = data[i + 1]

    # Check if the data already exists
    cursor.execute(f"SELECT id FROM data WHERE date='{date}' AND text='{text}'")
    result = cursor.fetchone()

    # Insert if it does not exist
    if not result:
        cursor.execute(f"INSERT INTO data (date, text) VALUES ('{date}', '{text}')")

# Commit and close the connection
conn.commit()
conn.close()

 

标签:cursor,Python,text,爬取,html,date,div,data
From: https://www.cnblogs.com/xlei/p/17104619.html

相关文章

  • python开发笔记--ImportError: cannot import name 'sysconfig' from 'distutils' (/u
    异常情况:ubuntu20.4安装python3.10和pip后,执行piplist提示如下:ImportError:cannotimportname'sysconfig'from'distutils'(/usr/lib/python3.8/distutils/__init__......
  • div支持拖动调整尺寸-html
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content=......
  • Vitualenvwrapper: 管理 python的 虚拟环境
            linux:install  Vitualenvwrapper[user]-3D05SQ3:~/python/managing-python-packages-virtual-environments/flask/venv$python3-mpipi......
  • 1、python_批量检测端口号
    #!/usr/bin/envpython#coding:utf-8#Author:zikangimportsocketlist_str='''172.31.7.1038080172.31.7.1046379172.31.7.1053306'''OK_list=[]Timeo......
  • 第04天-python函数与高阶函数
    1、函数和传实参1.1、Python函数1.1.1、函数的三分类数学定义y=f(x),y是x的函数,x是自变量。y=f(x0,x1,...,xn)Python函数由若干语句组成的语句块、函数名称、参......
  • 第02天-python线性数据结构
    1、数值处理1.1、内建常用数据类型1.1.1、分类数值型int、float、complex、bool序列sequence字符串str、字节序列bytes、bytearray列表list、元组t......
  • 第03天-python字节序列字典
    1、字节序列和切片1.1、字节序列Python3引入两个新的类型bytes、bytearray。bytes不可变字节序列;bytearray是可变字节数组。字节的世界里面没有编码1.2、编码与解......
  • Python,形参,实参,值传递,地址传递
    1.值传递在实参向形参传递的过程中,传递的只是实参的值,而在函数体操作的时候,实际操作的并不是实参而是形参,所以,值传递不改变原变量值。2.地址传递在实参向形参传递的过程中......
  • Python mock
    官方链接:https://docs.python.org/zh-cn/3/library/unittest.mock-examples.htmlMock备注:常用的有两个mock类:Mock和MagicMock,在多数示例中,Mock与MagicMock两个类......
  • 【视频】风险价值VaR原理与Python蒙特卡罗Monte Carlo模拟计算投资组合实例|附代码数
    原文链接:http://tecdat.cn/?p=22862 最近我们被客户要求撰写关于风险价值VaR的研究报告,包括一些图形和统计输出。风险价值(VaR)是一种统计数据,用于量化公司、投资组......