【问题标题】:How to get the date of a Twitter post (tweet) using BeautifulSoup?如何使用 BeautifulSoup 获取 Twitter 帖子(推文)的日期?
【发布时间】:2019-12-18 14:20:03
【问题描述】:

我正在尝试从 Twitter 中提取发布日期。我已经成功地提取了帖子的名称和文本,但日期对我来说是一个难题。

作为输入,我有一个这样的链接列表:

我正在使用按类别搜索,但我认为这是一个问题。有时它适用于某些链接,有时则不适用。我已经尝试过这些解决方案:

soup.find("span",class_="_timestamp js-short-timestamp js-relative-timestamp")
soup.find('a', {'class': 'tweet-timestamp'})
soup.select("a.tweet-timestamp")

但这些都不是每次都能奏效的。

我当前的代码是:

data = requests.get(url)                    
soup = BeautifulSoup(data.text, 'html.parser')
gdata = soup.find_all("script")    
for item in gdata:
items2 = item.find('a', {'class': 'tweet-timestamp js-permalink js-nav js-tooltip'}, href=True)                            
if items2:
items21 = items2.get('href')
items22 = items2.get('title')
print(items21)
print(items22)

我需要有发布日期的输出。

【问题讨论】:

    标签: python twitter beautifulsoup


    【解决方案1】:

    我相信 twitter API 将是最好的选择,但考虑到您的代码......

    它可以通过类tweet-timestamp 的元素的title 属性获得。此元素不在 script 标记内,这似乎是您正在搜索的位置:

    gdata = soup.find_all("script")    
    for item in gdata:
        items2 = item.find('a', {'class': 'tweet-timestamp js-permalink js-nav js-tooltip'}, href=True)   
    

    而是通过类直接选择:

    data = requests.get(link)                    
    soup = BeautifulSoup(data.text, 'html.parser')
    tweets = soup.find_all('div' , {'class': 'content'})    
    for item in tweets:
        items2 = item.find('a', {'class': 'tweet-timestamp js-permalink js-nav js-tooltip'}, href=True)                            
        if items2:
            items21 = items2.get('href')
            items22 = items2.get('title')
            print(items21)
            print(items22.split('-')[1].strip())
    

    我更喜欢 css 选择器,你只需要复合类中的一个类:

    data = requests.get(link)                    
    soup = BeautifulSoup(data.text, 'html.parser')
    tweets = soup.select(".content")    
    for item in tweets:
        items2 = item.select_one('.tweet-timestamp')                            
        if items2:
            items21 = items2.get('href')
            items22 = items2.get('title')
            print(items21)
            print(items22.split('-')[1].strip())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 2015-08-02
      相关资源
      最近更新 更多