Home > Back-end >  How to select Xpath element
How to select Xpath element

Time:12-02

I am playing around with connect automation in Linkedin and trying to send custom connection message to search list.

The way I do it, first I find all buttons. Then I find XPath of the names and index it. Then I fill all_names list. Then this names are inserted into greeting message.

The problem I face is that search result list does not only contain Connect buttons but also sometimes Follow button and that messes up the index, which results in wrong name being added to the greeting message.

Here is the code part:

driver.get(
    "https://www.linkedin.com/search/results/people/?network=["S"]&origin=FACETED_SEARCH&page=7")
time.sleep(2)
# ----------------------------------------------------------------

all_connect_buttons = driver.find_elements(By.TAG_NAME, 'button')
connect_buttons = [
    btn for btn in all_connect_buttons if btn.text == "Connect"]

all_names = []
all_span = driver.find_elements(
    By.XPATH, "//a[contains(@class,'app-aware-link ')]/span[@dir='ltr']/span[@aria-hidden='true']")

idx = [*range(1, 11)]
for j in range(len(idx)):
    #get only first name
    name = all_span[j].text.split(" ")[0]
    all_names.append(name)

    # print(name)

So basically I have types of buttons:

<span >
     Connect
</span>

and

<span >
     Follow
</span>

Is it somehow possible to filter only Connect button names so that Follow names are not added to all_span list? Can it be done with some XPath of Python expression?

CodePudding user response:

Instead of collecting all button elements you can make more precise locating.
This Xpath will give you "Connect" buttons only //button[contains(@aria-label,'Invite')].
So, instead of using this all_connect_buttons = driver.find_elements(By.TAG_NAME, 'button') you can use this:

all_connect_buttons = driver.find_elements(By.XPATH, "//button[contains(@aria-label,'Invite')]")

This can also be done with CSS Selectors

all_connect_buttons = driver.find_elements(By.CSS_SELECTOR, "button[aria-label*='Invite']")
  • Related