Home > Enterprise >  How to get links of elements filtering with more keywords with Selenium and Python?
How to get links of elements filtering with more keywords with Selenium and Python?

Time:09-28

From reference to this, How to get link from elements with Selenium and Python

I tried:

for a in driver.find_elements_by_xpath('.//span[contains(text(), "SPE8ED-21-Q-1288")]/a'):
    print(a.get_attribute('href'))

This showed the results as:

https://www.dibbs.bsm.dla.mil/Default.aspx
https://www.dibbs.bsm.dla.mil/Solicitations/Default.aspx
https://www.dibbs.bsm.dla.mil/RFQ/Default.aspx
https://www.dibbs.bsm.dla.mil/RFQ/RFQNsn.aspx?value=8145014862449&category=post&Scope=
https://dibbs2.bsm.dla.mil/Downloads/RFQ/8/SPE8ED21Q1288.PDF
https://www.dibbs.bsm.dla.mil/rfq/rfqrec.aspx?sn=SPE8ED21Q1288
https://www.dibbs.bsm.dla.mil/RA/Quote/QuoteFrm.aspx?sn=SPE8ED21Q1288

I am interested in getting only the link that contains Downloads keyword only.

In this case,

https://dibbs2.bsm.dla.mil/Downloads/RFQ/8/SPE8ED21Q1288.PDF

Any idea to do this filtering?

CodePudding user response:

Try like this:

for a in driver.find_elements_by_xpath('.//span[contains(text(), "SPE8ED-21-Q-1288")]/a'):
    if "Downloads" in a.get_attribute("href"):
        print(a.get_attribute('href'))

CodePudding user response:

You can filter Downloads keyword like this.

for a in driver.find_elements_by_xpath('.//span[contains(text(), "SPE8ED-21-Q-1288")]/a'):
    if "Downloads" in a.get_attribute('href'):
        print(a.get_attribute('href'))

Code Explanation :

we are getting a list of web elements and then looking (by iterating) for each and every web element for their attribute href ,if Downloads is found then print the href.

  • Related