instagram配置文件上第一篇文章的xpath不起作用(python、selenium、chromedriver)

2024-06-10 08:37:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在导航到任何Instagram个人资料后单击第一篇帖子。我查看了多个Instagram用户配置文件的第一篇帖子的xpath,它们似乎都是一样的。下面是梅西个人资料的一个例子

下面是我尝试使用chromedriver和python来点击梅西的第一篇文章。我已经导航到了https://www.instagram.com/leomessi/,这是梅西的个人资料

first_post_elem_click = driver.find_element_by_path('//*[@id="react-root"]/section/main/div/div[4]/article/div[1]/div/div[1]/div[1]/a/div').click()

但是,第一篇文章没有被点击。非常感谢您的帮助


Tags: 用户httpsdivcomwww配置文件文章chromedriver
3条回答

请检查下面的解决方案

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


Browser = webdriver.Chrome(executable_path=r"chromedriver.exe")

Browser.get("https://www.instagram.com/leomessi/")

WebDriverWait(Browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//body//div[contains(@class,'_2z6nI')]//div//div//div[1]//div[1]//a[1]//div[1]//div[2]"))).click()

您应该使用相对xpath,而不是使用绝对xpath。
您可以使用以下命令单击第一篇文章(还应用了显式等待):

WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "(//div[@class='Nnq7C weEfm']//img)[1]"))).click()

您需要添加以下导入:

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

我刚刚在Firefox中检查了这一点:$x('//*[@id="react-root"]/section/main/div/descendant::article/descendant::a[1]')。我想这会给你你想要的

相关问题 更多 >