Python爬虫脚本,Beautifulfly+MySql(源码)

'''
Created on 2020年4月15日

@author: zhangzhiwei
'''
import requests
from bs4 import BeautifulSoup  # 用来解析网页
import uuid
import pymysql
import time  # 导入时间隔

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 '
                  'Safari/537.36',
    'Accept-Language': 'zh-CN,zh;q=0.8'
}
conn = pymysql.connect(host='127.0.0.1', user='zhangzhiwei', passwd='zhangzhiwei', db='zhangzhang', charset='utf8')
cur = conn.cursor()
print("数据库已连接")
for i in range(1, 100):  # 爬取第一页到第100页的数据
    resp = requests.get(f"http://www.vegnet.com.cn/Price/List_p{i}.html")
    print(resp)  # 200: ok, 302:重定向, 404:页面丢失,500:服务器错误
    page_one = BeautifulSoup(resp.text, "html.parser")  # 通过html来,把请求的网页打印出来
    # 找到表格数据(table)
    dd = page_one.find('div', class_='pri_k').find_all("p")

    for ps in dd:  # tr是每一行内容,在所有的行中,遍历每一列的内容
        ss = ps.find_all("span")  # tds是每一列的内容,[第一列,第二列,第三列......]
        shopid=str(uuid.uuid1())
        shopDate = ss[0].text.strip('[]')  # 从第0项元素开始取值,取文本形式的内容数据,strip去掉左右两边所有的空格
        name = ss[1].text.strip()  # 获取名称,去掉左右空格
        market = ss[2].text.strip()  # 获取市场信息,去掉左右空格
        lowPrice = ss[3].text.strip()  # 获取最低价,去掉左右空格
        hightPrice = ss[4].text.strip()  # 获最高价格,去掉左右的空格
        avgPrice = ss[5].text.strip()  # 获取平均价格,去掉左右的空格
        unit = ss[6].text.strip()  # 获取单位,去掉左右空ge
        print(f"一个页面完事了{i}")
        sql="insert into pricedata(price_id,v_name,v_product,v_type,v_price,v_time) VALUES (%s,%s,%s,%s,%s,%s)"
        cur.execute(sql,(shopid,name,market,'0',avgPrice,shopDate))
        print("sql已执行")
    conn.commit()
    time.sleep(1)  # 防止服务器蹦了,间隔一秒钟
cur.close()
conn.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值