html网站开发软件,网站建设 sql 模版,绵阳汽车网站制作,调兵山网站数据来源#xff1a;
https://www.cngold.org/img_date/ 因为这个网站是数据随时变动的#xff0c;用requests、BeautifulSoup的方式解析html的话#xff0c;数据的位置显示的是“--”#xff0c;并不能取到数据。 所以采用webdriver访问网站#xff0c;然后从界面上获取…数据来源
https://www.cngold.org/img_date/ 因为这个网站是数据随时变动的用requests、BeautifulSoup的方式解析html的话数据的位置显示的是“--”并不能取到数据。 所以采用webdriver访问网站然后从界面上获取金价。
1、建表
在本地服务器上的mysql上建表主要字段sku、date_time、price分别对应产品也就是黄金、时间、价格
2、读取金价函数
这个函数主要就是读取金价并调用插入sql的函数 def extract_info(url,id):print(开始)chrome_options Options()chrome_options.add_argument(--disable-infobars)chrome_options.add_argument(--window-size1920,1080) # 可以设置浏览器窗口大小chrome_options.add_argument(--start-maximized) # 可以让浏览器窗口最大化chrome_options.add_argument(--disable-extensions) # 禁用扩展chrome_options.add_argument(--no-sandbox) # 以最高权限运行chrome_options.add_argument(--disable-dev-shm-usage) # 用于解决Chrome crash问题chrome_options.add_argument(--disable-browser-side-navigation) # 禁用浏览器端导航chrome_options.add_argument(--enable-automation) # 允许自动化chrome_options.add_argument(--headless) # 设置Chrome无头模式print(过程1)driverwebdriver.Chrome(optionschrome_options)driver.get(url)print(过程2)driver.maximize_window()#time.sleep(5)text_listdriver.find_element(bywebdriver.common.by.By.XPATH,value//html/body/div[3]/div/div[2]/div/div[3]/table/tbody/tr/td[2]/font)price_hourtext_list.textsql insert into reptile.gold_price_log values( str(id) , datetime.datetime.now().strftime(%Y-%m-%d %H:%M:%S) , str(price_hour) );print(sql)sql_insert(sql, id)数据插入函数 def sql_insert(sql,id):sqlsqlalchemy.text(sql)print(sql_getcnt(id))if sql_getcnt(id) 0:try:con.execute(sql)con.commit()except:print(执行失败)print(sql)3、数据验证函数
因为爬取数据的目标是每个小时记录一次为了避免测试、调试的数据干扰做一个验证的方法如果这个小时已经有数据了就不再运行上个函数了 def sql_getcnt(id):g_sql selectcount(*) as cntfrom reptile.gold_price_logwhere sku黄金and date_format(date_time,%Y-%m-%d %H:00:00) datetime.datetime.now().strftime(%Y-%m-%d %H:00:00) order by sku desc,date_time descg_sql sqlalchemy.text(g_sql)data pd.read_sql_query(sqlg_sql, concon, index_col[cnt])cnt list(data.index)[0]#print(cnt)return cnt4、主方法 url_list[https://www.cngold.org/img_date/]
sku_list[黄金]for i in range(len(sku_list)):print(sql_getcnt(sku_list[i]))if sql_getcnt(sku_list[i])100:time.sleep(random.uniform(1, 5))print(str(sku_list[i])已存在)else:url_idurl_list[i]extract_info(url_id,sku_list[i])
有些写法是之前脚本复制过来的所以偶尔会有些奇怪哈哈哈。
5、配置每小时调用
因为这个脚本是设置在了云服务器上所以要在linux服务器上设置定时执行我这边的逻辑是shell脚本调用python脚本然后定时执行shell脚本。
shell脚本内容 然后
crontab -e 这样就可以每小时记录金价了。