【问题标题】:When I run this my code, it returns '[]'. How can I fix this?当我运行我的代码时,它返回'[]'。我怎样才能解决这个问题?
【发布时间】:2019-01-08 20:48:23
【问题描述】:

我在 stackoverflow 中的第一个问题。我是python的初学者,我想请求任何喜欢的Instagram照片,但我的代码返回空

import requests
from bs4 import BeautifulSoup

url = "https://www.instagram.com/p/BsYt_megGfN/"
r = requests.get(url)
soup = BeautifulSoup(r.content,"html.parser")
data = soup.findAll("div",{"class","Nm9Fw"})
print(data)

我想查看喜欢这张照片但我不喜欢的人的名字。

【问题讨论】:

  • 空列表意味着soup.findAll在提取的html内容中没有找到任何divclass
  • beautifulsoup 的 html 解析器无法解析 javascript。

标签: python web-scraping beautifulsoup python-requests


【解决方案1】:

首先,对于抓取,您应该使用像 Anaconda 这样的预编译库。在此处下载:https://www.anaconda.com/download/ 并记住您的 python 可执行文件的路径。

因为 instagram 使用 javascript,您会返回一个空列表。 Requests 无法为您将 javascript 呈现为 html,因此您需要使用更强大的方法,例如 selenium。

试试这样的:

安装硒

在您的终端中:

conda install selenium

下载 Chrome 驱动程序

http://chromedriver.chromium.org/downloads

将 Selenium 导入您的代码

import os  
from selenium import webdriver  
from selenium.webdriver.common.keys import Keys  
from selenium.webdriver.chrome.options import Options  
from bs4 import BeautifulSoup

chrome_options = Options()  
chrome_options.add_argument("--headless")  

driver = webdriver.Chrome(executable_path="path-to-chromedriver",chrome_options=chrome_options)  
driver.get("https://www.instagram.com/p/BsYt_megGfN/")

html_source = driver.page_source  
driver.quit()

soup = BeautifulSoup(html_source,"html.parser")
data = soup.findAll("div",{"class","Nm9Fw"})
print(comments) # syntax for printing changes here for Python3

用你的 Anaconda 版本的 python 运行它。

【讨论】:

  • Nitpick:OP 必须使用 anaconda python 有什么特殊原因吗?据我所知,BS 和 selenium 都可以通过 pip 安装在 vanilla 中,就像通过 conda 一样容易
  • @G.Anderson 你的怀疑是正确的。由于 Python 2.7 中的许多函数缺乏原生 utf-8 支持,因此可能难以解决由于未知字符而发生的抓取问题。因此,由于 op 应该使用不同的安装,我认为增加 Anaconda 的稳定性会有所帮助。也许我对 conda 反应过度了?
  • @DanielScott 完全有道理,我不知道 utf-8 问题。我从 3.6 开始,从未回头。感谢您的解释!我想如果可能的话,另一个选择是如果 anaconda 太过分了,升级到 vanilla python 3,但这取决于 OPs 环境。
  • 如果可以的话,@wizardhopper 基本版本是该站点使用异步脚本来尝试阻止人们完全按照您的要求和漂亮的汤来做。 Selenium 是一个浏览器自动化包,它模仿网站上的实际用户,而不仅仅是发送网络请求。在上面发布的解决方案中,将打开一个新的 chrome 浏览器并查找/单击元素以获取您的数据
  • @wizardhopper 在代码 sn-p 中,插入您下载的 chromedriver 的路径。您下载了它,以便您可以在“无头”模式下运行抓取(即不需要出现浏览器窗口)。
猜你喜欢
  • 2013-10-24
  • 1970-01-01
  • 1970-01-01
  • 2019-04-10
  • 1970-01-01
  • 2012-03-16
  • 2019-06-13
  • 1970-01-01
  • 2020-11-28
相关资源
最近更新 更多