Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

Python Selenium XPath not getting urls from website

I'm pretty sure this is a website specific thing because I've tried my code (modified the xpath) on other sites and it works. I'm trying to get all the PDF links on the listed website in the code line.

driver.find_elements_by_xpath(xpath) yield empty list []

Code:

def scrape_url(url):
    
    xpath = '//*[@class="panel-body"]//a'
    
    options = Options()
    options.headless = True
    # change filepath of chromedriver
    driver = webdriver.Chrome(options=options, executable_path=r'C:UsersUserDesktopchromedriver')
    
    try:
        driver.get(url)
        all_href_elements = driver.find_elements_by_xpath(xpath)
        print("all_href_elements", all_href_elements) # <--empty list []
        for href_element in all_href_elements:
            article_url_text = href_element.text
            print(article_url_text)
            if article_url_text == "PDF":
                article_url = href_element.get_attribute('href')
                print(article_url_text, article_url)
                if article_url:
                    self.urls.add(article_url)
                    
        print("num of urls", len(self.urls))
            
    except Exception as e:
        print(e)
        print(url)

url = 'https://www.govinfo.gov/committee/senate-armedservices?path=/browsecommittee/chamber/senate/committee/armedservices/collection/BILLS/congress/106'

scrape_url(url)

enter image description here

But using the Chrome extension XPath Helper, the XPath query should return something. I think it might be due to how the urls are dynamic and aren't generated until the pane is "opened." But the url should call for the pane to be "open" for the web driver to get, no?

How would I get around this?

Thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Just use explicit wait for elements:

    all_href_elements = WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.XPATH,xpath))
    )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...