python爬虫示例爬取网页信息,并且将爬取到的信息存入数据库。

先展示一下效果图
在这里插入图片描述
因为我不需要这些数据,所以只爬取了三条,就关闭爬取了。
在这里插入图片描述
爬起到的图片(做课程作业时爬取的,同样的网站)
在这里插入图片描述

import request
import re
import mysql.connector as mysql
import requests
import urllib3
from bs4 import BeautifulSoup

def mysqlconnect():
    mydb = mysql.connect(
    host="localhost",       # 数据库主机地址
    user="root",    # 数据库用户名
    passwd="root",  # 数据库密码
    database="flowers"         #选择数据库
    )
    return mydb

def getHTMLText(url):
    try:
        r = requests.get(url, timeout = 30)
        r.raise_for_status()
        r.encoding = 'utf-8'
        return r.text
    except:
        return ""

def getinfo(soup,i):
    mydb=mysqlconnect()
    image=soup.select("#small-box > img")
    image[0]=str(image[0])
    image=re.findall(r'https:.+jpg|https:.+png',image[0])
    name=soup.select("#vi_details > h2")
    material=soup.select("#vi_details > div.introduce > div:nth-child(1) > div.dfr_td.centen")
    pack=soup.select("#vi_details > div.introduce > div:nth-child(2) > div.dfr_td.centen")
    language=soup.select("#vi_details > div.introduce > div:nth-child(3) > div.dfr_td.centen")
    gift=soup.select("#vi_details > div.introduce > div:nth-child(4) > div.dfr_td.centen")
    delivery=soup.select("#vi_details > div.introduce > div:nth-child(5) > div.dfr_td.centen")
    description=soup.select("#vi_details > div.introduce > div:nth-child(6) > div.dfr_td.centen")
    special=soup.select("#optimal")
    price=soup.select("#original")
    sellnum=soup.select("#vi_details > ul > li.first > span")
    print(image[0].strip())
    
    path='images//%s.jpg'%(str(i))
    r=requests.get(image[0].strip())
    with open(path,'wb') as f:
        f.write(r.content)
        f.close()
        print("图片保存cg")
    name[0]=name[0].get_text()
    print(name[0])
    material[0]=material[0].get_text()
    print(material[0])
    pack[0]=pack[0].get_text()
    print(pack[0])
    language[0]=language[0].get_text()
    print(language[0])
    gift[0]=gift[0].get_text()
    print(gift[0])
    delivery[0]=delivery[0].get_text()
    print(delivery[0])
    description[0]=description[0].get_text()
    print(description[0])
    special[0]=special[0].get_text()
    print(special[0])
    price[0]=price[0].get_text()
    print(price[0])
    sellnum[0]=sellnum[0].get_text()
    print(sellnum[0])
    mycursor=mydb.cursor()
    sql="insert into goods(goods_id,goods_images,goods_name,goods_material,goods_pack,goods_language,goods_gift,goods_delivery,goods_description,goods_special,goods_price,goods_sellnum)values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    val=(i,path,name[0],material[0],pack[0],language[0],gift[0],delivery[0],description[0],special[0],price[0],int(sellnum[0]))
    mycursor.execute(sql, val)
    mydb.commit()       #数据库有更新,必须使用到该语句
    print(mycursor.rowcount, "记录插入成功。")
    
def getContent(url,i):
    html = getHTMLText(url)
    #print(html)
    soup = BeautifulSoup(html, "html.parser")
    image=soup.select("#small-box > img")
    print(image)
    if image==[]:
        return
    else:
        getinfo(soup,i)
    

def main():
    for i in range(1,9000):
        url = "https://www.huaduocai.net/"+str(i)+".html"
        print(url)
        getContent(url,i)

main()

其中select中的CSS标签的获取可以查看这篇文章。
https://blog.csdn.net/qq_43597899/article/details/90111703

略记一下
函数mysqlconnect主要作用是连接MySQL数据库。
数据库的连接用到了mysql-connector包。也可以使用pymysql。

python -m pip install mysql-connector

函数getHTMLText作用是获取网页的源码(即你打开网页右键查看网页源代码内容一样)。

函数getinfo的作用比较多,第一是正则匹配出图片网址,用保存文件的方式保存到相对路径文件夹images内。第二是,get其他文本内容。第三就是将图片路径,及其他的文本信息存入数据库。
ps:存入数据库文本信息时,无论你的数据类型是什么,都用%s

函数getContent主要作用是将函数getHTMLText返回的源码,告诉“漂亮的汤”用HTML读它,并且判断这个网址是否存在。

原创文章 48 获赞 57 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_43597899/article/details/95760031