Python Selenium:无法在<time>标记中从Instagram获取HREF链接

2024-09-29 23:15:57 发布

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

PostLinkExtraction = driver.find_element_by_xpath("//article[1]/div[3]/div[1]/div/div[2]/div[1][*[local-name()='a']]").get_attribute('href')
print (PostLinkExtraction)

我正在尝试打印Instagram时间轴上第一篇帖子下Instagram时间戳中的href链接。由于某种原因,上面的代码返回none。下面是任何想要运行它并查看我可能出错的地方的人的代码,但我想要实现的总体目标是从<-时间>;标签。下面是<-时间>;标签将出现在开发者工具中

enter image description here

from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from time import sleep
from selenium.webdriver.common.keys import Keys
from selenium import webdriver

user = 'username'
passw = 'password'



driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://www.instagram.com/')
driver.implicitly_wait(10)

driver.find_element_by_name('username').send_keys(user)
driver.find_element_by_name('password').send_keys(passw)
Login = "//button[@type='submit']"
sleep(2)
driver.find_element_by_xpath(Login).submit()
sleep(1)
# Logs into Instagram
print ('Logged In')

#------------------------ATTENTION

NotNow = "//button[contains(text(),'Not Now')]"
driver.find_element_by_xpath(NotNow).click()
# Clicks Pop Up
print ('Close Pop Up')

# It's weird but the pop up opens once, only after this page.
# If ever a problem delete one, or have the first click be
# directed to your Instagram Profiles timeline

NotNow = "//button[contains(text(),'Not Now')]"
driver.find_element_by_xpath(NotNow).click()
#Clicks Pop Up; Comment out the line above if it causes an error
print ('Close Pop Up')

#-----------------------------------



driver.refresh()
print ('refreshing')
driver.implicitly_wait(10)
PostLinkExtraction = driver.find_element_by_xpath("//article[1]/div[3]/div[1]/div/div[2]/div[1][*[local-name()='a']]").get_attribute('href')
print (PostLinkExtraction)

Tags: namefromimportdivbydriverseleniumelement
2条回答

简短回答:停止使用XPath,通过以下方式找到您要查找的元素: 1-将具有相同标记的所有元素放在一个数组中

2-搜索使其唯一的两个或三个属性

3-在数组中循环提取并使用它

简单、快速、干净

我发现问题是因为您的xpath。修复它,您将打印出第一篇文章的href

PostLinkExtraction = driver.find_element_by_xpath("//article[1]/div[3]/div[1]/div/div[2]/div[1]/a").get_attribute('href')
print (PostLinkExtraction)

结果是:

enter image description here

相关问题 更多 >

    热门问题