简体   繁体   English

在 LinkedIn 上使用 Selenium 和 Python

[英]Using Selenium with Python on LinkedIn

I am in the process of building a script using python and selenium which clicks on the 'message button' on my network to send a default message.我正在使用 python 和 selenium 构建脚本,该脚本单击网络上的“消息按钮”以发送默认消息。

Linkedin uses dynamic fields (ember), so it's not possible to find elements by id. Linkedin 使用动态字段(ember),因此无法通过 id 查找元素。 So far I have tried:到目前为止,我已经尝试过:

driver.find_elements_by_class_name("...").click()
driver.find_element_by_tag_name("button").click()
driver.find_element_by_css_selector("...").click()
driver.find_element_by_xpath(//...)

This is my code so far:到目前为止,这是我的代码:

def TextBot(browser):
time.sleep(3)
browser.get('https://www.linkedin.com/mynetwork/invite-connect/connections/')
time.sleep(3)
xpath = '//button[contains(@aria-label,"Send message to")]'
time.sleep(3)
buttons = driver.find_element_by_xpath(xpath)
for btn in buttons:
    print("Can %s" % btn.get_attribute("aria-label"))  

def Main():
#Parse enail and password to the script
parser = argparse.ArgumentParser()
parser.add_argument('email', help='linkedin email')
parser.add_argument('password', help='linkedin password')
args = parser.parse_args()

#browse to the login page
browser = webdriver.Firefox()
browser.get('https://linkedin.com/uas/login')

#Parse the two argument in the login form
emailElement = browser.find_element_by_id('session_key-login')
emailElement.send_keys(args.email)
passElement = browser.find_element_by_id('session_password-login')
passElement.send_keys(args.password)
passElement.submit()

#Initialise ViewBot function
os.system('clear') #cls rather than clear on windows
print ("[+] Success! Logged In, Bot Starting")
#ViewBot(browser)
TextBot(browser)
browser.close()

And my error:而我的错误:

File "LinkedInBot.py", line 88, in TextBot buttons = driver.find_element_by_xpath(xpath) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 393, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 966, in find_element 'value': value})['value'] File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 320, in execute self.error_handler.check_response(response) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //button[contains(@aria-label,"Send mess文件“LinkedInBot.py”,第 88 行,在 TextBot 按钮 = driver.find_element_by_xpath(xpath) 文件“/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote /webdriver.py”,第 393 行,在 find_element_by_xpath 中返回 self.find_element(by=By.XPATH, value=xpath) 文件“/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages /selenium/webdriver/remote/webdriver.py", line 966, in find_element 'value': value})['value'] File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ site-packages/selenium/webdriver/remote/webdriver.py”,第 320 行,在执行 self.error_handler.check_response(response) 文件“/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site -packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //button[contains(@ aria-label,"发送混乱age to")]年龄到")]

Is there anything else I am not thinking about?还有什么我没有考虑的吗?

By the way thanks for the answers so far.顺便感谢到目前为止的答案。 I am close but I still think there is some other form of encryption to bypass我很接近,但我仍然认为还有一些其他形式的加密可以绕过

"Message button" in Linkedin looks like this: Linkedin 中的“消息按钮”如下所示:

<button class="message-anywhere-button mn-connection-card__message-btn button-secondary-medium" aria-label="Send message to John Smith" data-ember-action="" data-ember-action-5128="5128">
  <span aria-hidden="true">Message</span>
  <span class="visually-hidden">
    Send a message to John Smith
  </span>
</button>

So for locator you have several options, lets settle on most primitive one: look for Send message to text inside aria-label :因此,对于定位器,您有多种选择,让我们选择最原始的一种:在aria-label查找Send message to text :

xpath = '//button[contains(@aria-label,"Send message to")]'

This locator will find all buttons.此定位器将找到所有按钮。 But depending on which function you call, you may end up choosing only first element, or all elements.但是根据您调用的函数,您最终可能只选择第一个元素或所有元素。 Lets say the goal is to collect all the buttons:假设目标是收集所有按钮:

xpath = '//button[contains(@aria-label,"Send message to")]'
all_message_buttons = driver.find_elements(By.XPATH, xpath)
for message_button in all_message_buttons:
    print("Can %s" % message_button.get_attribute("aria-label")) 
    # prints Can Send Message to John Smith
    # and any other names available on page

Finally, before selecting buttons you need to make sure that page was loaded and buttons are indeed displayed.最后,在选择按钮之前,您需要确保页面已加载并确实显示了按钮。 There are various ways to do that, but I usually just replace finding elements I need with waiting for them:有多种方法可以做到这一点,但我通常只是用等待它们来替换我需要的查找元素:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# ...
xpath = '//button[contains(@aria-label,"Send message to")]'
wait = WebDriverWait(browser, 10) # wait for up to 10 sec
all_message_buttons = wait.until(EC.presence_of_element_located((By.XPATH, xpath)))
for message_button in all_message_buttons:
    print("Can %s" % message_button.get_attribute("aria-label")) 
    # prints Can Send Message to John Smith
    # and any other names available on page

Code below scroll down until all contacts have been loaded.下面的代码向下滚动,直到所有联系人都已加载。
Then get all message buttons, click, send and close message window.然后获取所有消息按钮,单击、发送和关闭消息窗口。

from selenium.webdriver.support import expected_conditions as EC
import re

#...

wait = WebDriverWait(driver, 20)
connectionsHeader = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".mn-connections__header h2"))).text
totalConnections = int(re.findall(r"\d+", connectionsHeader))
while len(driver.find_elements_by_css_selector(".mn-connections li")) < totalConnections-1:
    driver.execute_script("window.scrollTo(0, 100);")

messageButtons = driver.find_elements_by_css_selector(".mn-connections li button.mn-connection-card__message-btn")

for button in messageButtons:
    button.click()
    wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".msg-form__contenteditable"))).click()
    driver.find_elements_by_css_selector(".msg-form__contenteditable").send_keys('message')
    driver.find_elements_by_css_selector(".js-msg-close").click()
    wait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR, ".js-msg-close")))

Not: code may contains typos or small errors.不是:代码可能包含拼写错误或小错误。 Feel free to improve it .随意改进它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM