使用Python的BeautifulSoup库从HTML中提取元素

时间:2018-09-11 06:07:27

标签: python html beautifulsoup instagram instagram-api

我正在寻找从Instagram提取数据并记录发布时间而不使用auth的方式。

下面的代码为我提供了IG帖子中页面的HTML,但我无法从HTML中提取时间元素。

from requests_html import HTMLSession
from bs4 import BeautifulSoup
import json

url_path = 'https://www.instagram.com/<username>'
session = HTMLSession()
r = session.get(url_path)

soup = BeautifulSoup(r.content,features='lxml')
print(soup)

I would like to extract data from the time element near the bottom of this screenshot

2 个答案:

答案 0 :(得分:0)

要提取时间,您可以使用html标签及其类:

time = soup.findAll("time", {"class": "_1o9PC Nzb55"}).text

答案 1 :(得分:0)

我猜您共享的图片是浏览器检查器的屏幕截图。尽管检查代码是Web抓取的一个很好的基本准则,但是您应该检查BeautifullSoup得到了什么。如果检查soup的打印,您会看到正在寻找的数据在script标签内是一个json。因此,您的代码和其他任何针对time标签的解决方案都不适用于BS4。您可能会尝试使用硒。 无论如何,这里使用您截图中的instagram使用BeautifullSoup伪解决方案:

from bs4 import BeautifulSoup
import json
import re
import requests
import time

url_path = "https://www.instagram.com/srirachi9/"
response = requests.get(url_path)
soup = BeautifulSoup(response.content) 
pattern = re.compile(r"window\._sharedData\ = (.*);", re.MULTILINE)
script = soup.find("script", text=lambda x: x and "window._sharedData" in x).text

data = json.loads(re.search(pattern, script).group(1))

times = len(data['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges'])
for x in range(times):
    time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges'][x]['node']['taken_at_timestamp']))

times变量是json包含的时间戳量。它可能看起来像地狱,但这只是耐心地遵循json结构并据此建立索引的问题。