【发布时间】:2018-05-31 20:23:34
【问题描述】:
看起来 Instagram 网页上的 <class id> 对应于 <img class> 每天都在变化。现在它是FFVAD,明天它会是别的东西。例如(我把它缩短了,链接很长):
<img class="FFVAD" alt="Tag your best friend" decoding="auto" style="" sizes="293px" src="https://scontent-lax3-2.cdninstagram.com/vp/0436c00a3ac9428b2b8c977b45abd022/5BAB3EBC/t51.2885-15/s640x640/sh0.08/e35/33110483_592294374461447_8669459880035221504_n.jpg">
也就是说,我需要修复脚本并对Class ID 进行硬编码,以便能够抓取网页。
var = driver.find_elements_by_class_name('FFVAD')
有人告诉我,我可以使用img.get_attribute('class') 找到class ID 并将其存储起来以备后用。但我仍然不明白这是如何实现的,因此 selenium 或 soup 可以从 html tag 中获取 Class ID 并稍后存储或解析它。
我现在得到的就是这个。这有点脏,而且不对,但想法就在那里。
import requests
import selenium.webdriver as webdriver
url = ('https://www.instagram.com/kitties')
driver = webdriver.Firefox()
driver.get(url)
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
imgs_dedupe = driver.find_elements_by_class_name('FFVAD')
for img in imgs_dedupe:
posts = img.get_attribute('class')
print posts
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(scroll_delay)
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
当我运行它时,我得到了这个输出,因为页面上有 3 张图片,我得到了 3x Class ID
python tag_print.py
FFVAD
FFVAD
FFVAD
【问题讨论】:
-
Instagram 需要注册才能访问任何内容,所以我无法给出具体示例。
-
只有在检查元素时才能查看。无需注册或登录
-
哦,所以首页也可以使用。变化很重要。
-
是的,你可以去instagram.com/kitties查看所有内容,因为个人资料最长是公开的
-
找到带有
alt="Tag your best friend"的图像,获取它的类,然后用它来搜索具有相同类的其他元素。
标签: python selenium web-scraping