使用Selenium制作类似Instagram的机器人时遇到问题。 我正在尝试编写通过图片的代码(如果喜欢的话),但是它不起作用。 这是我的代码:
def Like_photoTags_and_commnet(self,hashtag,comment):
driver=self.driver
driver.get("https://www.instagram.com/explore/tags/" + hashtag + "/")
time.sleep(2)
pic_hrefs = []
for i in range(1,3):
driver.execute_script("window.scrollTo(0,document.scrollHeight);")
time.sleep(2)
#searching for pictures link
hrefs_in_view = driver.find_elements_by_tag_name('a')
# finding relevant 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 unique photos
[pic_hrefs.append(href) for href in hrefs_in_view if href not in pic_hrefs]
print("Check: pic href length " + str(len(pic_hrefs)))
for pics in pic_hrefs:
driver.get(pics)
#if picture liked then continue
if driver.find_element_by_xpath("//button/span[@aria-label='UnLike']"):
continue
else:
driver.find_element_by_xpath("//button/span[@aria-label='Like']").click()
if comment in driver.page_source:
continue
else:
driver.find_element_by_class_name("Ypffh").click()
for letter in comment:
driver.find_element_by_class_name("Ypffh").send_keys(letter)
time.sleep(random.randint(1,2))
driver.find_element_by_class_name("Ypffh").send_keys(Keys.ENTER)
time.sleep(5)
我在控制台中收到此错误。 问题出在第52行。你们有什么建议吗?
Traceback (most recent call last):
File "C:/Users/behro/PycharmProjects/untitled/Test.py", line 52, in Like_photoTags_and_commnet
if driver.find_element_by_xpath("//button/span[@aria-label='UnLike']"):
File "C:\Users\behro\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "C:\Users\behro\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
'value': value})['value']
File "C:\Users\behro\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\behro\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//button/span[@aria-label='UnLike']"}
(Session info: chrome=74.0.3729.157)
(Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17763 x86_64)
答案 0 :(得分:3)
您正在尝试查找不存在的元素!因此出现错误:
NoSuchElementException:消息:没有这样的元素
因此您可以使用except
和for pics in pic_hrefs:
driver.get(pics)
#if picture liked then continue
try:
driver.find_element_by_xpath("//button/span[@aria-label='UnLike']"):
except NoSuchElementException:
driver.find_element_by_xpath("//button/span[@aria-label='Like']").click()
。
from selenium.common.exceptions import NoSuchElementException
不要忘记导入它:sleep
现在,您的g.io("graph.xml").write().iterate()
应该使用WebDriverWait
。
希望这对您有帮助!
答案 1 :(得分:1)
在这里提供了一个寻找主题标签追随者的示例工作。为了实现完全自动化,只需在我的github页面上进行操作即可。这仅出于信息和研究目的,因此,如果对“找不到类”或“找不到元素”有任何问题,只需进行更改检查元素并更改标签/类名称。发生这种情况是因为他们不断更改路径和名称
https://www.github.com/deshwalmahesh
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
import random
from random import randint
import os
def update_file():
with open('hashtags.txt') as f:
main_list=f.read().splitlines()
return(main_list)
def format(num):
x=num.replace(',','')
num=int(x)
if num>999 and num<=999999:
x=num%1000
y=num//1000
return(str(y)+'.'+str(x)[0]+'K')
elif num>999999:
x=num%1000000
y=num//1000000
return (str(y) + '.' + str(x)[0] + ' M')
else: return (num)
br=webdriver.Chrome()
br.get('https://www.instagram.com/accounts/login/')
time.sleep(5)
br.find_element_by_name('username').send_keys('username')
br.find_element_by_name('password').send_keys('password',Keys.ENTER)
time.sleep(5)
main_list=update_file()
count=0
while True:
try:
br.get('https://www.instagram.com')
time.sleep(3)
if "Turn on" in br.page_source:
x=br.find_element_by_class_name('mt3GC')
a=x.find_elements_by_tag_name('button')
a[1].click()
time.sleep(2)
for i in range(count,len(main_list)):
tag=(str(main_list[i]))
a=tag.strip()
tag=a.lower()
a=tag.replace(' ','')
tag=a.replace('\n','')
a=tag.replace('\t','')
br.get('https://www.instagram.com/explore/tags/'+a)
print(a)
time.sleep(7)
find=br.find_elements_by_xpath("//*[@class='g47SY ']")
time.sleep(2)
posts=find[0].text
post=format(posts)
print(post)
with open('posts.txt', 'a') as f:
x = str(post)
f.write('%s\n' % x)
with open('tags.txt', 'a') as f:
x = '#'+a
f.write('%s\n' % x)
time.sleep(3)
count+=1
except Exception as e:
print(e)
pass