我有下面的代碼,下面的代碼將從 pluang.com 站點獲取值,但我想制作 2 種顏色,以免混淆并且易于理解。
我想要如果報廢值低于 (-) 860,000 (mis. 850.000) 那么印刷品必須是紅色的,如果它高于 ( ) 860,000 (mis. 870.000) 那么印刷品必須是綠色的。
任何人都可以幫忙嗎?謝謝你。
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
from datetime import datetime
import time
import os
class bcolors:
SELL = '\033[92m'
BUY = '\033[31;1m'
os.system("clear")
while True:
url = "https://pluang.com/produk/pluang-emas"
UserAgent = Request(url, headers={'User-Agent':'Mozilla/5.0'})
html = urlopen(UserAgent)
data = BeautifulSoup(html, "html.parser")
items = data.findAll("h1", {"id":"gold-price"})
for item in items:
print(bcolors.BUY " SELL GOLD:",item.get_text().strip(),"-",datetime.now())
time.sleep(59)
uj5u.com熱心網友回復:
您已經擁有了為終端著色的課程。您將需要以某種方式獲取值(您正在顯示它)檢查它是否比您的條件更大或更小,然后相應地列印。
在您的代碼item.get_text()列印是這樣的:Rp860.530/g。我相信這里 Rp 是貨幣,g 是克。讓我們擺脫它們:
import re
numbers = rr = list(map(float, re.findall("[- ]?[.]?[\d] (?:,\d\d\d)*[\.]?\d*(?:[eE][- ]?\d )?", item.get_text())))
見:https : //stackoverflow.com/a/4289348/2681662
這會將文本中的所有數字作為串列回傳。
現在我們可以檢查該值是否小于或大于我們的閾值。
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
from datetime import datetime
import time
import os
import re
class bcolors:
BUY = '\033[92m'
SELL = '\033[31;1m'
os.system("clear")
while True:
url = "https://pluang.com/produk/pluang-emas"
UserAgent = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
html = urlopen(UserAgent)
data = BeautifulSoup(html, "html.parser")
items = data.findAll("h1", {"id": "gold-price"})
for item in items:
rr = list(map(float, re.findall("[- ]?[.]?[\d] (?:,\d\d\d)*[\.]?\d*(?:[eE][- ]?\d )?", item.get_text())))
if rr[0] < 860:
print(bcolors.SELL " SELL GOLD:", item.get_text().strip(), "-", datetime.now())
else:
print(bcolors.BUY " BUY GOLD:", item.get_text().strip(), "-", datetime.now())
time.sleep(59)
我不確定紅色和綠色部分是否正確寫入。你無論如何都可以改變它。
uj5u.com熱心網友回復:
我認為這就是你所追求的。你的問題肯定暗示你在問如何列印顏色。如果您只是說您需要知道如何提取價格,您會得到更集中的答案。
這里只回傳一個價格,所以內部回圈看起來很傻。
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
from datetime import datetime
import time
import os
class bcolors:
SELL = '\033[92m'
BUY = '\033[31;1m'
WHITE = '\033[37m'
url = "https://pluang.com/produk/pluang-emas"
while True:
UserAgent = Request(url, headers={'User-Agent':'Mozilla/5.0'})
html = urlopen(UserAgent)
data = BeautifulSoup(html, "html.parser")
item = data.findAll("h1", {"id":"gold-price"})[0].get_text()
price = int(item.strip('Rp/g').replace('.',''))
if price > 860000:
print(bcolors.SELL " SELL GOLD:",item,"-",datetime.now())
else:
print(bcolors.BUY " BUY GOLD:",item,"-",datetime.now())
print(bcolors.WHITE,end='')
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/349382.html
標籤:Python
下一篇:從多個類繼承多個同名方法
