php抓取网页数据插入数据库(以爬取糗事百科中24小时网页中第一列表页 )

优采云 发布时间: 2021-11-13 11:25

  php抓取网页数据插入数据库(以爬取糗事百科中24小时网页中第一列表页

)

  以尴尬百科24小时网页第一页的所有文章内容、作者、搞笑号、评论号为例,将爬取到的四项保存到mysql数据库中。

  思路:存储在数据库中,需要使用数据库中的表,所以我们先创建一个名为'myblog'的数据库,然后在这个数据库中创建一个名字

  名为'qiushi'的表可以使用命令符号输入到mysql数据库中,并使用mysql语句创建。也可以使用 Navicat Premium 软件直接连接 mysql 数据库,在

  直接在可视化界面上操作。如下图所示,在qiushi表中创建以下类型的字段。

  

  然后需要使用python连接数据库,需要使用pymsql模块,该模块是python的第三方模块,需要导入下载。然后创建连接的语句显示在以下程序中:

  # mysql数据库服务器,端口:3306,而且确保服务器是处于启动状态

# 安装pymysql:pip install pymysql

import pymysql

# 建立连接

conn = pymysql.connect('127.0.0.1','root','密码','myblog',charset='utf8')

# 建立游标

cursor = conn.cursor()

# 数据库操作

# (1)定义一个格式化的sql语句

sql = 'insert into qiushi(author,funny_num,comment_num,content) values(%s,%s,%s,%s) '

# (2)准备数据

data = ('nancy','30','100','太好笑了')

# (3)操作

try:

cursor.execute(sql,data)

conn.commit()

except Exception as e:

print('插入数据失败',e)

conn.rollback() #回滚

# 关闭游标

cursor.close()

# 关闭连接

conn.close()

  由于我们在做项目的时候不可能把这段代码拼接到我们爬取的程序文件中,我们可以把这些语句封装成一个类的形式,每次爬取

  蠕虫完成后,可以直接在程序中实例化一个类对象,然后在类中调用存储在数据库中的方法来保存数据。

  封装的类形式如下程序所示;

  第一个是settings.py文件,用来写连接mysql数据的各种参数,连接的ip,端口,mysql数据库密码,连接的数据库名

  # 该文件存储项目中的所有配置参数

MYSQL_HOST = '127.0.0.1'

MYSQL_USER = 'root'

MYSQL_PWD = '密码'

MYSQL_DB = 'myblog'

  创建类的文件:

  # mysql数据库服务器,端口:3306,而且服务器是处于启动状态

# 安装pymysql:pip install pymysql

import pymysql

import threading

from settings import MYSQL_HOST,MYSQL_DB,MYSQL_PWD,MYSQL_USER

class DataManager():

# 单例模式,确保每次实例化都调用一个对象。

_instance_lock = threading.Lock()

def __new__(cls, *args, **kwargs):

if not hasattr(DataManager,"_instance"):

with DataManager._instance_lock:

DataManager._instance = object.__new__(cls)

return DataManager._instance

return DataManager._instance

def __init__(self):

# 建立连接

self.conn = pymysql.connect(MYSQL_HOST,MYSQL_USER,MYSQL_PWD,MYSQL_DB,charset='utf8')

# 建立游标

self.cursor = self.conn.cursor()

def save_data(self,data):

# 数据库操作

# (1)定义一个格式化的sql语句

sql = 'insert into qiushi(author,funny_num,comment_num,content) values(%s,%s,%s,%s) '

# (2)准备数据

# data = ('nancy','30','100','太好笑了')

# (3)操作

try:

self.cursor.execute(sql,data)

self.conn.commit()

except Exception as e:

print('插入数据失败',e)

self.conn.rollback() #回滚

def __del__(self):

# 关闭游标

self.cursor.close()

# 关闭连接

self.conn.close()

  然后就可以直接爬行了。在爬虫程序中,可以先在类文件中引入类名,实例化创建类对象,然后直接调用类中的save_data方法将爬取到的数据存入数据中。

  具体程序如下:

  import requests

from lxml import etree

from datamanage import DataManager

# 实例化数据库类对象

db = DataManager()

# 判空

def getDataFormList(temp_list):

if len(temp_list) > 0:

return temp_list[0].strip()

else:

return ''

# 接口

base_url = 'https://www.qiushibaike.com/hot/page/%d/'

# 网络请求

for page in range(1,2,1):

# url = 'https://www.qiushibaike.com/hot/page/%d/'%(page)

url = base_url%(page)

headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'

}

# response = requests.get(url,headers = headers,)

response = requests.request('get',url = url,headers = headers,verify = False )

with open('qiushi.html','w',encoding=response.encoding) as fp:

fp.write(response.text)

# 数据提取

tree = etree.HTML(response.text)

h2_list = tree.xpath('//h2/text()')

# 先定位到文章列表

article_list = tree.xpath('//div[contains(@id,"qiushi_tag_")]')

for article in article_list:

# 作者

author_list = article.xpath('./div/a/h2/text()')

author = getDataFormList(author_list).strip()

# print('作者:',author)

# 好笑数

funny_number_list = article.xpath('.//i[@class="number"]/text()')

funny_number = getDataFormList(funny_number_list)

# print('好笑数:',funny_number)

# 评论数

comment_list = article.xpath('.//a[@class="qiushi_comments"]/i/text()')

comment = getDataFormList(comment_list).strip()

# print('评论数:',comment)

# 段子内容

content_list = article.xpath('.//div[@class="content"]/span/text()')

content = getDataFormList(content_list).strip()

# print('段子内容:',content)

print(author,content,comment,funny_number,)

# 图片链接

# pic_list = article.xpath('')

# 数据存储

# data = (author,content,comment,funny_number)

# 注意此处存储数据时,要和插入mysql表中的mysql语句中的字段相对应,否则会报错。

data = (author,funny_number,comment,content)

db.save_data(data)

  运行后的数据库结果如下:

  

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线