【发布时间】:2019-04-11 12:38:25
【问题描述】:
我正在以下 Instagram 页面上测试 Instagram:https://www.instagram.com/acmilan/ 并尝试获取帖子元素(现在 = '4,552 个帖子')。 如果我检查页面,HTML 看起来就像随附的屏幕截图。 我定位该元素的代码是:
driver = webdriver.Chrome
soup = BeautifulSoup(driver.page_source, 'html.parser')
elements = soup.find_all("ul", text=re.compile("posts"))
print(len(elements))
但这没有找到任何东西。 然后,我尝试了:
elements = soup.find_all("span", text=re.compile("posts"))
print(len(elements))
还是什么都没有。 然后,我尝试了:
elements = soup.find_all(True, text=re.compile('posts'))
这似乎是一项很容易的任务,但不知何故我找不到解决方案。有什么建议? 谢谢
【问题讨论】:
-
数据是通过 JavaScript 呈现的,因此无法通过 BeautifulSoup 访问,因为 BS 只能访问静态 HTML。您可能需要使用 Selenium 来呈现 ReactJS 内容,然后可以使用 BeautifulSoup 解析这些内容,类似于此问答:Scraping elements rendered using React JS with BeautifulSoup
-
我正在尝试编辑我的问题,但找不到解决方法。我忘了提到“soup = BeautifulSoup(driver.page_source, 'html.parser')”和驱动来自 selenium。
-
在这种情况下,您的代码在我运行时可以正常工作。尝试使用:
elements = soup.find('span', {'class': "g47SY "}); print(elements.text) -
@davedwards 谢谢戴夫。问题是,我需要使用文本“post”而不是类值来查找元素,因为这经常发生变化。你能想出一个基于关键字“post”的解决方案吗?谢谢
-
是的,我可以提供解决方案,但首先您检查过以下任何答案吗?