python - 使用 Inspect 元素进行抓取

标签 python twitter beautifulsoup instagram screen-scraping

我试图通过抓取 Instagram 来获取一些信息。我已经在 Twitter 上尝试过这段代码,它运行良好,但它在 Instagram 上没有显示任何结果,这两种代码都可以在这里找到。


推特代码:

from bs4 import BeautifulSoup
from urllib2 import urlopen
theurl = "https://twitter.com/realmadrid"
thepage = urlopen(theurl)
soup = BeautifulSoup(thepage,"html.parser")
print(soup.find('div',{"class":"ProfileHeaderCard"}))

结果:完美给出。


Instagram 代码:​​

from bs4 import BeautifulSoup
from urllib2 import urlopen
theurl = "https://www.instagram.com/barackobama/"
thepage = urlopen(theurl)
soup = BeautifulSoup(thepage,"html.parser")
print(soup.find('div',{"class":"_bugdy"}))

结果:无

最佳答案

如果您查看源代码,您会看到内容是动态加载的,因此没有 div._bugdy在您的请求返回的内容中,根据您想要的内容,您可以从脚本 json 中提取它:

import requests
import re
import json

r = requests.get("https://www.instagram.com/barackobama/")
soup = BeautifulSoup(r.content)
js = soup.find("script",text=re.compile("window._sharedData")).text
_json = json.loads((js[js.find("{"):js.rfind("}")+1]))
from pprint import pprint as pp

pp(_json)

这为您提供了在 <script type="text/javascript">window._sharedData = ..... 中看到的所有内容在返回的来源中。

如果你想获得关注者,那么你需要使用类似 selenium 的东西, 该站点几乎都是动态加载的内容,要获得关注者,您需要单击仅在您登录后才可见的链接,这将使您更接近您想要的内容:

from selenium import webdriver
import time
login = "https://www.instagram.com"
dr = webdriver.Chrome()

dr.get(login)

dr.find_element_by_xpath("//a[@class='_k6cv7']").click()
dr.find_element_by_xpath("//input[@name='username']").send_keys(youruname")
dr.find_element_by_xpath("//input[@name='password']").send_keys("yourpass")
dr.find_element_by_css_selector("button._aj7mu._taytv._ki5uo._o0442").click()
time.sleep(5)
dr.get("https://www.instagram.com/barackobama")

dr.find_element_by_css_selector('a[href="/barackobama/followers/"]').click()
time.sleep(3)
for li in dr.find_element_by_css_selector("div._n3cp9._qjr85").find_elements_by_xpath("//ul/li"):
    print(li.text)

这会在您单击链接后从出现在弹出窗口中的 li 标签中提取一些文本,您可以从无序列表中提取任何您想要的内容:

enter image description here

关于python - 使用 Inspect 元素进行抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37854569/

相关文章:

python - 将 python 装饰器应用于所有继承类

python - Matplotlib:如何为绘图的背景颜色添加效果?

android - 使用我的 Android 应用程序中的 Oauth 在 Twitter 中的 CALLBACK_URL 上放置什么?

android - 从 Android 应用程序打开 Twitter 帐户

swift - 如何使用 UIActivityViewController 创建用户交互式推文或 Facebook 帖子

python - 如何使用pyquery python触发事件

python - Snow Leopard 上的 SQLite 最大查询参数不同?

python - Pandas 将 nan 替换为基于另一列的第一个非 nan 值

python - XPath 不适用于屏幕抓取

python - 我想使用 beautifulsoup 搜索具有指定类的 div 和 <a>