Seite 1 von 1

Selenium

Verfasst: Freitag 2. Juli 2021, 15:20
von Schlummerman
Hallo! Ich habe mich heute mal hier angemeldet, in der Hoffnung das mir hier jemand helfen kann!

Und zwar möchte über Selenium im Chrome Browser eine Webseite aufrufen und einen Textarea beschreiben.

Wie folgt: er wählt den Link an, ruft diese auch auf.

Nun lässt sich aber nicht der Text einfügen.

Der Code:


commentBox = driver.find_element(
By.XPATH, "/html/body/div[1]/section/main/section/div[1]/form/textarea" )

commentBox.click()

commentBox.send_keys(CONFIGS['comment'])

postButton = driver.find_element(By.XPATH, "/html/body/div[1]/section/main/section/div/form/button")

postButton.click()


Der Button wird geklickt, aber es wird kein Text eingefügt.

Woran liegt das?

Danke im voraus! :)

Re: Selenium

Verfasst: Freitag 2. Juli 2021, 15:40
von __deets__
Ohne die Webseite zu kennen, und den vollstaendigen Code, kann man das nicht beurteilen.

Re: Selenium

Verfasst: Freitag 2. Juli 2021, 22:08
von Schlummerman
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
from selenium.webdriver.common.by import By
import time


CONFIGS = {
'USERNAME': 'Username',
'PASSWORD': 'passwort',
'HASHTAGS': [
'Art', 'illustration', 'drawing', 'draw', 'picture', 'artist', 'sketch', 'sketchbook', 'paper', 'pen', 'pencil', 'artsy', 'instaart', 'instagood', 'gallery', 'creative', 'photooftheday', 'instaartist', 'graphic', 'graphics', 'artoftheday', 'originalpainting', 'painting', 'masterpiece', 'trendy', 'ootd', 'ootn', 'outfitoftheday', 'vintage', 'fashiongram', 'fashioninsta', 'chic', 'elegant', 'streetstyle', 'fashionable', 'hautecouture', 'instafashion', 'trendy', 'fashiondaily', 'fashionaddict', 'menwithstyle', 'fashiongoals', 'fashionlife', 'instastyle', 'passion4fashion', 'mylook', 'fashiondiaries', 'casualstyle', 'urbanstyle', 'fashionlovers', 'fashionblogger', 'fashioninspiration', 'fashionmen', 'fashiontrends', 'fashiongirl', 'fashionillustration', 'graphicdesigner', 'photoshop', 'design', 'designer', 'logodesigning', 'mockup', 'illustratoroninstagram', 'prints', 'printshop', 'printsforsale', 'printstudio', 'artprints', 'colours', 'colourful', 'colourpop', 'colourpopme', 'colourfull', 'brush', 'brushlettering', 'brushpen', 'brushcalligraphy', 'brushes', 'pencildrawing', 'pencilart', 'pendrawing', 'penandinc', 'penart', 'pencilsketch', 'shirtdesign', 'designinspiration', 'designideas', 'designlovers', 'designstudio', 'designgrafico', 'print', 'printmaking', 'cotton', 'clothing', 'clothingbrand', 'clothingline', 'clothingboutique', 'clothingstore', 'kidsclothing', 'styleblogger', 'stylefashion', 'styleinspiration', 'sytlediary', 'stylepost', 'styleinfluencer', 'stylegram', 'stylegoals', 'styleguide', 'styleblog', 'styleinspo', 'styleoftheday', 'ootd', 'ootn', 'stylemen', 'styles', 'styleformen', 'styleiswhat', 'styletips', 'stylediaries', 'styled', 'stylebook', 'stylelife', 'stylemepretty', 'styleaddict', 'styleicon', 'stylebloggers', 'fashionstyle', 'menstyle', 'bloggerstyle', 'vintagestyle', 'bohostyle', 'stylefile', 'styledbyme', 'shop', 'shoponline', 'shoppingonline', 'shopthelook', 'onlinestore', 'etsystore', 'brand', 'branding', 'mensfashion', 'business', 'follow', 'blog', 'blogger', 'moda', 'digitalmarketing', 'marketing', 'brandshop', 'brandstrategy', 'brandstylist', 'brandstore', 'brandstyle', 'brandwelove', 'smallbusiness', 'packaging', 'startup', 'digital', 'printing', 'contentmarketing', 'blogstyle', 'madewell', 'ootdfash', 'dtg', 'fashionkilla', 'todayiamwearingthis', 'digitalart', 'everydaymadewell', 'lifestyleblog', 'ootdgermany', 'newblogpost', 'digitalpainting', 'digitaldrawing', 'digitalillustration', 'digitalartist', 'acolorstory', 'colorhunters', 'colocrush', 'digitalsketch', 'colorlove', 'digitalartwork', 'dailydoseofcolor', 'digitalcollage', 'digitaldesign', 'visualcrush', 'pantone', 'pastelover', 'abmlifeiscolorful', 'vscocommunity'


],


'COMMENT': ['Nice!'],

'TOTAL_LIKES_PER_HASHTAG': 5,
'SYSTEM': 'mac'
}

total_likes = 0

driver = webdriver.Chrome(executable_path="/Users/florian/Downloads/chromedriver")

print("Loading Instagram")
driver.get("https://www.instagram.com/")

print("Logging in")

WebDriverWait(driver, 10).until(EC.presence_of_element_located((
By.NAME, 'username'
)))

usernameInput = driver.find_element(By.NAME, 'username')
usernameInput.send_keys(CONFIGS['USERNAME'])

passwordInput = driver.find_element(By.NAME, 'password')
passwordInput.send_keys(CONFIGS['PASSWORD'])

passwordInput.submit()


start = time.time()

# Search
WebDriverWait(driver, 10).until(EC.presence_of_element_located((
By.XPATH, "/html/body/div[1]/section/nav/div[2]/div/div/div[2]/input"
)))
print("Logged in!")

print("Navigating through hashtags...")
for current_hashtag in CONFIGS['HASHTAGS']:
driver.get(
"https://www.instagram.com/explore/tags/ ... t_hashtag)
)

try:
# Search results
WebDriverWait(driver, 10).until(EC.presence_of_element_located((
By.TAG_NAME, "h1"
)))
except:
print("Hashtag #{} not loaded, going to next...".format(current_hashtag))
continue

print("Loaded #{}".format(current_hashtag))

print("Checking for results...")
results = driver.find_elements(By.XPATH, "//a[contains(@href, '/p/')]")

if not results:
print("No results for #{}".format(current_hashtag))
driver.quit()

print("Opening first post from #{}...".format(current_hashtag))
results[0].click()

current_hashtag_likes = 0
while current_hashtag_likes < CONFIGS['TOTAL_LIKES_PER_HASHTAG']:
try:
WebDriverWait(driver, 10).until(EC.presence_of_element_located((
By.TAG_NAME, "time"
)))
except:
print("Something is wrong in URL: {}".format(driver.current_url))
driver.quit()

time.sleep(4)

try:
likeButton = driver.find_element(
By.XPATH, "/html/body/div[5]/div[2]/div/article/div[3]/section[1]/span[1]/button/div/span"
)

likeButton.click()


print("[#{}/{}/{}] Liked: {}".format(
current_hashtag,
current_hashtag_likes,
CONFIGS['TOTAL_LIKES_PER_HASHTAG'],
driver.current_url
))

total_likes = total_likes + 1
current_hashtag_likes = current_hashtag_likes + 1
time.sleep(1)
except Exception as e:
print(e)
pass

try:

commentBox = driver.find_element(
By.XPATH, "/html/body/div[1]/section/ main/section/div[1]/form/textarea" )

commentBox.click()

commentBox. send_keys(CONFIGS['comment'])

postButton = driver.find_element(By. XPATH, "/html/body/div[1]/section/main/section/div/form/button")

postButton.click()

try:
WebDriverWait(driver, 10).until(EC.presence_of_element_located((
By.CLASS_NAME, 'coreSpriteRightPaginationArrow'
)))

nextButton = driver.find_element(
By.CLASS_NAME, 'coreSpriteRightPaginationArrow'
)

nextButton.click()
except:
print("Something wrong, going to next hashtag...")
break


print("Exiting...")
print("=====================")
print("Total posts liked: {}".format(total_likes))
driver.quit()
driver.close()

Dies ist der Code und die Webseite wäre Instagram. Das Liken funktioniert schon mal echt gut, nur das "kommentieren" leider überhaupt nicht.

Re: Selenium

Verfasst: Samstag 3. Juli 2021, 14:18
von Sirius3
Der Code hat viele Syntaxfehler, das ist also nicht der, den Du ausführst.
Zumdem hast Du viele nackte excepts, die das Programm in einen definierte Zustände versetzen kann. Welche Meldungen bekommst Du denn alle? Ist da eine dabei, die das Verhalten erklären könnten?

Re: Selenium

Verfasst: Samstag 3. Juli 2021, 14:28
von Schlummerman
Die Syntaxfehler sind wohl vom Copy&Paste entstanden.

Also tatsächlich läuft der Code ohne Probleme. Er Liket den Post, geht zum nächsten über und wiederholt das ganze über die angegebene Anzahl.

Er klickt das dazugehörige Textfeld an, fügt aber leider die Comments nicht ein.

Diese Fehler Meldung wird beim einsetzen der Keys angezeigt:

" 'WebDriver' object has no Attribute 'findElement' "
Oder

" 'WebDriver object has no Attribute 'sendKeys' "

Re: Selenium

Verfasst: Samstag 3. Juli 2021, 14:31
von __deets__
Nirgendwo in dem von dir gezeigten Code kommt “findElement” vor. Also passt der Code nicht zur Fehlermeldung, oder du paraphrasierst die Fehler, statt die wirklichen zu nennen. Beides ist nicht hilfreich.

Re: Selenium

Verfasst: Samstag 3. Juli 2021, 14:40
von Schlummerman
oh Entschuldigung:

" 'WebDriver' object has no Attribute 'find_element' "
Oder

" 'WebDriver object has no Attribute 'send_keys' "

dies waren die Fehler Meldungen

aktuell sehen die Zeilen so aus:


try:
likeButton = driver.find_element(
By.XPATH, "/html/body/div[5]/div[2]/div/article/div[3]/section[1]/span[1]/button/div/span"
)

likeButton.click()
time.sleep(5)

commentKey = driver.find_element(
By.XPATH, "/html/body/div[5]/div[2]/div/article/div[3]/section[3]/div[1]/form/textarea"
)
driver.execute_script("arguments[0].click();", element)

commentKey.send_keys("Very Nice!")
time.sleep(3)

commentKey.submit()



print("[#{}/{}/{}] Liked: {}".format(
current_hashtag,
current_hashtag_likes,
CONFIGS['TOTAL_LIKES_PER_HASHTAG'],
driver.current_url
))

total_likes = total_likes + 1
current_hashtag_likes = current_hashtag_likes + 1
time.sleep(1)
except Exception as e:
print(e)
pass

Dabei erscheint keinerlei Fehlermeldung oder sonst was, er macht aber auch nicht was er soll

Dies ist der HTML code den ich ansprechen muss:

<textarea aria-label="Kommentar hinzufügen ..." placeholder="Kommentar hinzufügen ..." class="Ypffh" autocomplete="off" autocorrect="off" style="height: 18px !important;"></textarea>

Dies der dazugehörige XPATH:
/html/body/div[5]/div[2]/div/article/div[3]/section[3]/div/form/textarea

ich hatte versucht über die Element_ID dies anzusprechen, leider besitzt diese garkeine ID, wahrscheinliche von IG selbst so programmiert, damit weniger Bots spamen können.

Re: Selenium

Verfasst: Samstag 3. Juli 2021, 20:23
von Schlummerman
Ich habe die Lösung bereits gefunden!

Es lag an der Seite selbst, sobald nämlich die Textarea angeklickt wurde hat sich der HTML Code auch verändert und musste nochmal angesprochen werden.

Danke trotzdem :)