Python:简单的爬虫程序,从web页面爬取图片与标题并保存MySQL
文章目录
- 一、环境说明
- 二、基本思路
- 三、代码
一、环境说明
python 版本:3.10
MySQL版本:8
二、基本思路
首先,我们需要查看网页源代码
通过html源码,确定我们要抓取的内容所在标签的特点
然后,利用BeautifulSoup进行html代码解析
在逐一获取我们需要的标签即可。
最后,将图片下载到本地,基本信息保存到MySQL
三、代码
import os # 同来创造文件夹
from bs4 import BeautifulSoup # 用来解析回应的数据
import pymysql
import requests # 发送请求和得到响应用的def main(pages):filepath = os.getcwd() + '\myImgs\\' # 创造一个文件夹if not os.path.exists(filepath): # 如果没有则创造os.makedirs(filepath)#创建数据库连接# 连接 MySQL 数据库db = pymysql.connect(host='127.0.0.1', # 主机名port=3306, # 端口号,MySQL默认为3306user='root', # 用户名password='root', # 密码database='test', # 数据库名称)cur = db.cursor()img_url = ""context = ""local_path = ""for page in range(pages):url = "https://www.huffpost.com/news/?page=" + str(page+1) # 第几页print(url)r = requests.get(url, verify=False) #取消SSL验证soup = BeautifulSoup(r.text, 'html.parser') # html.parser是解析器divs = soup.find_all(name='div', attrs={'class': ['card card--standard js-card']}) # 根据class值,获取对应的divfor item in divs:title = item.find(name='h3', attrs={'class': ['card__headline__text']})context = title.text #读取标签内容image = item.find(name='img', attrs={'width': ['368']})img_url = image.get('src') # 获取图片url地址imgcontent = requests.get(img_url).content # 获取图片的二进制数据filename = img_url[img_url.index('asset/') + 6:img_url.rfind('.')] + '.jpeg'# filename = str(fnum) + '.jpg'local_path = str(filepath).replace("\\", "\\\\") + filenamewith open(filepath + filename, 'wb') as wf: # 二进制形式写入数据wf.write(imgcontent)sql = 'INSERT INTO `test`.`py_news` (`img_url`, `context`, `local_path`) VALUES ( "' + img_url + '", "' + context + '", "' + local_path + '");'print(sql)cur.execute(sql) # 引号中为SQL语句r.close() # 关闭连接# 关闭数据库连接cur.close()db.close()if __name__ == '__main__':main(3)