python - 如何获取特定字符串并返回他的 css 背景颜色
问题描述
我正在尝试抓取一个包含基于时间的“热图”的网站。
我在 python 中有一个代码,可以获取当前时间并将其转换为变量。
我有我的代码来抓取这个网站。
我正在尝试根据当前时间提取 div tr th 的背景颜色。
例如,假设现在是 19:13 点
我想返回包含字符串 19:13 的 div的元素背景颜色,然后在我的代码的另一部分中使用此信息。
使用下面的代码,我可以获得表 id 'map-responsive' 中包含的所有元素,如何正确获取基于变量 current_time_hora 的信息
谢谢。
from bs4 import BeautifulSoup
from datetime import datetime
import requests
now = datetime.now()
current_time_hora = now.strftime("%H:%M")
print("Current Time - Hora =", current_time_hora)
headers = requests.utils.default_headers()
headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0'})
data3 = requests.get('http://www.tradertimerzone.com.br/web/index.php?r=operation%2Fmaps&model=5-15', headers=headers)
if data3.status_code == requests.codes.ok:
info = BeautifulSoup(data3.text, 'html.parser')
encontraHorarios2 = ((info.findAll('table', {'id': 'map-responsive'})))
print(encontraHorarios2)
解决方案
import requests
from bs4 import BeautifulSoup
import time
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0",
}
params = {
"r": "operation/maps",
"model": "5-15"
}
def main(url, now):
with requests.Session() as req:
req.headers.update(headers)
req.params = params
req.head(url)
r = req.get(url)
soup = BeautifulSoup(r.text, 'lxml')
target = soup.select_one(
f'th:-soup-contains("{now}")')['style']
print(target)
if __name__ == "__main__":
now = time.strftime('%H:%M')
print(f"Current Time: {now}")
main('http://www.tradertimerzone.com.br/web/index.php', now)
输出:
Current Time: 01:42
;background:#00B050
推荐阅读
- python - Python Tkinter 文本小部件中的随机 { }
- resttemplate - Resttemplate无法解析T类型的结果,但能够得到LinkedHashMap的结果
- angular - Struts 1.3项目中的Angular11 html找不到资源
- angular - 如何在一段时间后无休止地显示模态?
- c++ - 这个散列函数中的键值使用了多少位?
- elasticsearch - 在 vega-lite 中将图例添加到子弹图
- javascript - 在 vscode 调试器中查看导入的变量时遇到问题 - Javascript 和反应
- javascript - Discord js v13频道过滤器不起作用
- python - highcharts 不是 Ipython 中的函数
- reactjs - 在 GET 请求开始之前等待 POST 请求完成(React/Node)