[我知道做一个基于INSTAGRAM API的机器人更好,但是我制作了一个硒火狐,它已经在几个月前工作了,但是我知道我想再次运行它,不再喜欢图片了
def like_photo(self, hashtag):
driver = self.driver
driver.get("https://www.instagram.com/explore/tags/" + hashtag + "/")
time.sleep(2)
# gathering photos
pic_hrefs = []
for i in range(1, 7):
try:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2)
# getting hashtags
hrefs_in_view = driver.find_elements_by_tag_name('a')
# finding hrefs
hrefs_in_view = [elem.get_attribute('href') for elem in hrefs_in_view
if '.com/p/' in elem.get_attribute('href')]
# building list of photos
[pic_hrefs.append(href) for href in hrefs_in_view if href not in pic_hrefs]
except Exception:
continue
# Liking photos
unique_photos = len(pic_hrefs)
for pic_href in pic_hrefs:
driver.get(pic_href)
time.sleep(2)
try:
time.sleep(random.randint(2, 4))
like_button = driver.find_element_by_xpath('/html/body/div[4]/div[2]/div/article/div[2]/section[1]/span[1]/button').click()
# liking photo
like_button().click()
time.sleep(random.randint(1, 2))
except Exception as e:
time.sleep(2)
unique_photos -= 1
以上是通过给定的#标签收集照片然后喜欢它们的代码,收集部分可以正常工作,但不会发生。也许这是XPATH的问题?那是我最初的想法,但是如果是这种情况,我应该改用哪种方法呢?
代码确实可以正常工作,并且您只应更改查找“ like_button”的行
而不是:
like_button = driver.find_element_by_xpath('/html/body/div[4]/div[2]/div/article/div[2]/section[1]/span[1]/button').click()
使用此:like_button = driver.find_element_by_xpath('//*[@aria-label="Like"]').click()
如果以前曾奏效,并且您未更改过代码,则可能是因为站点进行了一些更改
[我建议尽量少使用xpath并优先使用ID名称类...如果它们在某些导航器中没有唯一的名称,则可以右键单击检查器中的元素并复制xpath
也使用您的代码,如果您希望所有人都喜欢,则只单击其中的一个:
Likes=driver.findElementsById(id)
for x in likes:
x.click()