【问题标题】:Having real trouble finding element on Selenium using python to scrape Instagram在 Selenium 上使用 python 抓取 Instagram 时遇到了真正的麻烦
【发布时间】:2020-07-28 10:29:29
【问题描述】:

我在爬取 Instagram 时遇到了很大的困难,并且尝试了所有方法并打算放弃,我不确定我做错了什么,但似乎无法抓住页面上的全部关注者。我已经尝试过其他帖子提供的代码,但无济于事。我尝试使用 driver.find_elements_by_class_name 以及 xpath 来抓取元素。

我在下面单独尝试过(如果第一次不起作用,则转到下一个,显然不是同一时间)没有任何运气:

data  = driver.find_elements_by_class_name("g47SYlOXF2")
data  = driver.find_elements_by_class_name("g47SY lOXF2")
data  = driver.find_elements_by_class_name("g47SY.lOXF2")

上面每次都返回一个空列表。

我也尝试过 Xpath:followers = driver.find_element_by_xpath(followers_x),followers_x 分别是以下尝试。每次都找不到元素

followers_x ='//*[@id="react-root"]/section/main/div/ul/li[2]/a/span'
followers_x = '//*[@id="react-root"]/section/main/div/ul/li[2]/a'
followers_x = '//*[@id='react-root']/section/main/article/header/div[2]/ul/li[2]/a/span'
followers_x = "//span[@id='react-root']//span[@title]"
followers_x = "//a[@span='g47SY lOXF2']"
followers_x = './/*[contains(text(), "followers")]/span'

followers = followers_x.get_attribute("title")

每次尝试都会给我一个 selenium.common.exceptions.NoSuchElementException

我很难受……谁能告诉我我做错了什么?!

【问题讨论】:

  • 请阅读为什么screenshot of HTML or code or error is a bad idea。考虑使用基于格式化文本的相关 HTML、代码试验和错误堆栈跟踪来更新问题。
  • 试试driver.find_element_by_xpath("//li[@class='Y8-fY '][2]/a/span").text

标签: python-3.x selenium web-scraping instagram


【解决方案1】:

要从关注者那里获得标题,您需要诱导 WebDriverWait() 并等待 visibility_of_element_located() 并关注 xpath。

print(WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,"//a[contains(.,' followers')]/span"))).get_attribute('title')) 

您需要导入以下库。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2013-11-11
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多