【问题标题】:Unable to scrape some timestamp attached to a text from a webpage无法从网页中抓取附加到文本的某些时间戳
【发布时间】:2020-09-13 12:28:23
【问题描述】:

我正在尝试从网页中抓取附加到文本的timestamp。我可以完美地抓取文本,但找不到时间戳。不过,我可以从那里刮掉附加到 cmets 的其他时间戳。 cmets 中的时间戳可以在脚本标签中找到,作为created_at 的值。但是,我找不到我要的那个。

website url

我试过了:

import re
import json
import requests

url = 'https://www.instagram.com/p/CEuX_8iH95S/'

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'
    r = s.get(url)
    script_tag = json.loads(re.findall(r"window\._sharedData = (.*?});",r.text)[0])
    post_content = script_tag['entry_data']['PostPage'][0]['graphql']['shortcode_media']['edge_media_to_caption']['edges'][0]['node']['text']
    print(post_content)

如何从上面的网站解析附加到文本的时间戳?

【问题讨论】:

    标签: python python-3.x web-scraping python-requests


    【解决方案1】:

    您可以使用datetime 模块中的.fromtimestamp() 方法解析时间戳。

    这是怎么做的:

    import datetime
    import re
    import json
    import requests
    
    url = 'https://www.instagram.com/p/CEuX_8iH95S/'
    
    with requests.Session() as s:
        s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'
        r = s.get(url)
        script_tag = json.loads(re.findall(r'window\._sharedData = (.*?});', r.text)[0])
        post_date = script_tag['entry_data']['PostPage'][0]['graphql']['shortcode_media']['taken_at_timestamp']
    
        print(datetime.datetime.fromtimestamp(post_date).isoformat())
        print(datetime.datetime.fromtimestamp(post_date).strftime("%b %d %Y %H:%M:%S"))
    

    打印出来:

    2020-09-04T20:25:49
    Sep 04 2020 20:25:49
    

    如果您想了解有关日期格式的更多信息,请查看文档here

    【讨论】:

    • 您的解决方案似乎有效,但该站点中的日期与您建议的脚本生成的日期之间存在细微差异。鉴于那里是sep 05。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    相关资源
    最近更新 更多