我有一個作業用的webscraper,可以從我們的非公開網站上下載給定過濾器的所有pdf。我試圖將檔案命名為"ID Number File name date file was made.pdf"我在 Try 陳述句中對檔案名使用了絕對的xPath,但它沒有發揮作用,并跳轉到了例外。我希望有人能幫我看看我是否在語法上遺漏了什么,或者是否有更好的方法來實作這一點。我也復制了xPath,看看是否有更有經驗的人可以給我一個相對的xPath來使用
Error:
selenium.common.exceptions.NoSuchElementException: 訊息:沒有這樣的元素。無法定位元素。{"method":"xpath","selector"。 "/html/body/div[1]/div[1]/div[4]/div/div[2]/div/div[2]/div/div[1]/div[1]/h2"}。
(會話資訊:chrome=93.0.4577.63)
HTML:
我的代碼:
table_rows=driver.find_elements_by_xpath("/a[contains(@href, '#resources/details/?id=')]"/span>)
for link_elem in table_rows:
url = link_elem.get_attribute('href')
id_number= url[-8:]
driver.get(url)
try:
filename_first = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[4]/div/div[2]/div/div[2]/div/div[1]/div[1]/h2'/span>) 。 text.replace(' :', '').replace(r'/', '-')
except:
filename_first = 'file.pdf'.
#filename_first = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[4]/div/div[2]/div/div[2]/div/div[1]/div[1]/div[2]/h2').text.replace(' :, '' ).replace(r'/' , '-')
filename_final = id_number filename_first # ' .pdf'
css_thing = '#file > div:nth-child(1) > div.form-group.padding-xs-bottom > div > div > button.btn.btn-danger.get-download-url' /span>
time.sleep(5)
download_button = driver.find_element_by_css_selector(css_thing)
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, css_thing)).click()
time.sleep(5)
link_data = driver.find_element_by_xpath("/a[ contains(@href, 'https://s3.amazonaws.com')]")
url = link_data.get_attribute("href")
r = requests.get(url, allow_redirects=True)
open(filename_final, 'wb').write(r.content)
print("good")
uj5u.com熱心網友回復:
你得到了NoSuchElement例外,因為你使用了絕對的xPath,如果DOM是動態的,你的腳本將有很多機會失敗。
總是使用可靠的xPath
xPath: /a/div[@class='flex-1 ellipsis padding-xs-right']
uj5u.com熱心網友回復:
基于你所分享的快照,我相信你可以使用下面的xpath
//a[contains(@href,'#resources/details/')]//div[contains(@class,'ellipsis') ]
另外,在使用這個xpath之前,在Dev工具中檢查我們是否有1/1匹配節點。
像這樣使用它 :
filename_first = driver.find_element_by_xpath("/a[contains(@href,'#resources/details/')]/div[contains(@class,'ellipsis') ] ") .text
print(filename_first)
如果你用上面的代碼得到了想要的輸出,我們可以用regex代替它來得到你真正想要的東西。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/309754.html
標籤:

