我试图提取游戏统计的MLB游戏使用BeautifulSoup。到目前为止,它运行得很好,但我只是注意到,我无法使用通常的方法检索有关游戏开始时间的信息:
soup.findAll("span",{"class":“时间游戏-时间”})
奇怪的是,它找到了确切的元素,并允许我打印它,它表明,除了文本之外,汤已经找到了元素的所有内容。不幸的是,文字部分是我所需要的。
图片:
有疑问的网址:http://www.espn.com/mlb/game?gameId=370925110
不需要使用像Selenium这样的way驱动程序就可以解决这个问题吗?
代码:
with urllib.request.urlopen(link) as url:
page = url.read()
soup = BeautifulSoup(page, "html.parser")
clock = soup.findAll("span", {"class": "time game-time"})
print(clock[0])
发布于 2018-02-22 14:53:08
虽然通常您需要做一些反向工程,这里没有消耗外部API来填充游戏时间。
游戏的时间戳可以在页面源的脚本标记中作为变量找到。
简单的漂亮汤就足够得到时间戳了:
js = str(soup.findAll("script", {"type": "text/javascript"}))
s = 'espn.gamepackage.timestamp = "'
idx = js.find(s) + len(s)
ts = ""
while js[idx] != '"':
ts += js[idx]
idx += 1
print(ts)
# 2017-09-25T17:05Z
时间戳以UTC为单位,如尾随Z所示。要转换为不同的时区,可以使用python-dateutil
。
from datetime import datetime
from dateutil import tz
ts = datetime.strptime(ts, "%Y-%m-%dT%H:%MZ")
ts = ts.replace(tzinfo=tz.gettz('UTC'))
target_tz = ts.astimezone(tz.gettz('Europe/Berlin'))
print(target_tz)
发布于 2018-02-22 13:53:06
这是因为这个特定的span
标记由javascript填充。
如果您想自己查看它,请在浏览器上打开URL并查看页面的代码源以找到这个范围,您将看到:
<span class="time game-time" data-dateformat="time1" data-showtimezone="true"></span>
(或者curl 'http://www.espn.com/mlb/game?gameId=370925110' | grep 'time game-time'
,随便吧)
所以你必须在这里解决:
selenium
https://stackoverflow.com/questions/48928968
复制相似问题