我想从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
提取时间你可以使用html标签及其类:
time = soup.findAll("time", {"class": "_1o9PC Nzb55"}).text
我猜你所分享的图片是一个浏览器检查器截图。虽然检查代码是Web抓取的一个很好的基本准则,但您应该检查BeautifullSoup正在获得什么。如果你检查soup
的打印,你会看到你正在寻找脚本标签内的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结构和相应的索引。