此函数def get_heart_icon_X path(post_num)错误 pl z帮助运行代码
我正在尝试为Instagram编写自己的bot python selenium bot,以进行一些实验。我成功登录并喜欢在搜索栏中的首页供稿页面上,将我带到以下网页:网页
但是我不知道如何喜欢提要中的照片,我尝试使用XPath和以下路径进行搜索:“ // [@ id =” reactroot“] / section / main / article / div1 / div / div / div / div1 / div1 / a / div”但这没有用,有人有想法吗?
from selenium import webdriver
chrome_path = r"C:\---\chromedriver.exe"
import time
class InstagramBot:
def __init__(self, username,password):
self.username = username
self.password = password
self.driver = webdriver.Chrome(chrome_path)
def closeBrowser(self):
self.driver.close()
def login(self):
driver = self.driver
driver.get("https://www.instagram.com/")
time.sleep(2)
login_button = driver.find_element_by_xpath("""//*[@id="react-root"]/section/main/article/div[2]/div[2]/p/a""")
login_button.click()
time.sleep(2)
user_name_elem = driver.find_element_by_xpath("//input[@name='username']")
user_name_elem.clear()
user_name_elem.send_keys(self.username)
passwwarword_elem = driver.find_element_by_xpath("//input[@name='password']")
passwwarword_elem.clear()
passwwarword_elem.send_keys(self.password)
time.sleep(2)
nextButton = driver.find_element_by_xpath("""//*[@id="react-root"]/section/main/div/article/div/div[1]/div/form/div[3]/button""")
nextButton.click()
time.sleep(2)
offer_elem = driver.find_element_by_xpath ("""//div/h2[text()='Turn on Notifications']""")
dismiss_elem = driver.find_element_by_xpath ("""//button[text()='Not Now']""" )
dismiss_elem.click()
time.sleep(2)
nextButt = driver.find_element_by_class_name("""//*[@id="react-root"]/section/main/section/div[1]/div[1]/div/article[1]/div[2]/section[1]/span[1]/button/span""")
nextButt.click()
time.sleep(2)
def get_heart_icon_xpath(post_num):
"""
Return heart icon xpath corresponding to n-post.
"""
if post_num == 1:
return 'xpath=//button/span'
else:
return f'xpath=//article[{post_num}]/div[2]/section/span/button/span'
try:
# Get xpath of heart icon of the 19th post.
my_xpath = get_heart_icon_xpath(19)
heart_icon = driver.find_element_by_xpath(my_xpath)
heart_icon.click()
print("Task executed successfully")
except Exception:
print("An error occurred")
andreyIG = InstagramBot("usr","pasw")
andreyIG.login()
andreyIG.get_heart_icon_xpath(19)