使用Python 抓取数据并写入Mysql数据库

import re

import requests
import pymysql
from bs4 import BeautifulSoup

def spideData(page):
    conn = pymysql.connect(host='118.190.8.4', user='shici', password='shici', database='shici', port=3306)
    cursor = conn.cursor()
    cursor.execute(
         "create table if not exists tangshi(id int(11) NOT NULL AUTO_INCREMENT,title varchar(100),author varchar(50),content text,PRIMARY KEY (`id`))")

    url="https://so.gushiwen.cn/shiwens/default.aspx?page="+str(page)+"&tstr=&astr=&cstr=&xstr=诗"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
    }
    html=requests.get(url=url,headers=headers).text
    soup=BeautifulSoup(html,'lxml')
    titleList=soup.select('div.sons p b')
    authorList=soup.select('.sons p.source')
    contentList=soup.select('.sons .contson')

    index=0
    for title in titleList:
        query="insert into tangshi (title,author,content) values (%s,%s,%s)"
        cursor.execute(query,(title.text.strip(),authorList[index].text.strip(),contentList[index].text.strip()))
        index+=1

    conn.commit()
    cursor.close()
    conn.close()

if __name__=="__main__":
    for i in range(2,10):
        spideData(i)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Python爬取数据并将其写入数据库,您需要使用以下步骤: 1. 安装必要的库:您需要安装Python库来进行爬取和数据库连接。例如,requests库用于发出HTTP请求,beautifulsoup4库用于解析HTML,以及MySQLdb或SQLAlchemy库用于连接数据库。 2. 连接数据库:您需要连接您的数据库。如果您使用MySQL数据库,则可以使用MySQLdb库。如果您使用其他类型的数据库,则可以使用适当的库。 3. 爬取数据:您需要使用requests和beautifulsoup4库来爬取数据。您可以使用requests库发出HTTP请求并获取HTML响应。接下来,您可以使用beautifulsoup4库解析HTML并提取所需的数据。 4. 将数据写入数据库:一旦您从网站上抓取了所需的数据,您需要将其插入到数据库中。您可以使用MySQLdb或SQLAlchemy库来实现这一点。您需要编写一个SQL查询,然后将数据作为参数插入数据库中。 以下是一个示例代码,它使用PythonMySQLdb库从网站上爬取书籍数据并将其保存到MySQL数据库中: ```python import requests from bs4 import BeautifulSoup import MySQLdb # 连接数据库 db = MySQLdb.connect(host="localhost", user="root", passwd="", db="books") cursor = db.cursor() # 爬取数据 url = "https://www.example.com/books" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") books = soup.find_all("div", class_="book") # 将数据写入数据库 for book in books: title = book.find("h2").text.strip() author = book.find("p", class_="author").text.strip() sql = "INSERT INTO books (title, author) VALUES (%s, %s)" values = (title, author) cursor.execute(sql, values) db.commit() db.close() ``` 请注意,此代码仅供参考,并且需要根据您的具体情况进行更改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值