'''
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()
Python爬虫脚本,Beautifulfly+MySql(源码)
最新推荐文章于 2023-05-25 17:57:58 发布