我正在嘗試從 CAG 網站下載多個 PDF(鏈接https://cag.gov.in/en/state-accounts-report?defuat_state_id=64)。我正在使用以下代碼-
url='https://cag.gov.in/en/state-accounts-report?defuat_state_id=64'
response=requests.get(url)
response
soup=BeautifulSoup(response.text,'html.parser')
soup
for link in soup.select("a[href$='.pdf']"):
print(link)
for link in soup.select("a[href$='.pdf']"):
filename = os.path.join(folder_location,link['href'].split('/')[-1])
with open(filename, 'wb') as f:
f.write(requests.get(urljoin(url,link['href'])).content)
這給了我整個頁面的所有 PDF,我希望僅在“每月關鍵指標”選項卡下下載 PDF。請建議對代碼進行必要的更改以執行此操作。
uj5u.com熱心網友回復:
您可以嘗試縮小從中選擇鏈接的選項卡的范圍。標簽 id 可以使用
tabId = soup.find(
lambda t: t.name == 'a' and t.get('href') and
t.get('href').startswith('#tab') and # just in case
'Monthly Key Indicators' == t.get_text(strip=True)
).get('href')
(或者,如果它總是相同的 id,你可以設定為tabId = "#tab-360"。)然后,你可以將你的選擇更改為
soup.select(f"{tabId} a[href$='.pdf']")
但是,您不是在每個報告中下載 3 次相同的檔案嗎?您可以將您的 for 回圈更改為僅從帶有“下載”作為文本的鏈接下載:
pdfLinks = soup.select(f"{tabId} a[href$='.pdf']")
pdfLinks = [pl for pl in pdfLinks if pl.get_text(strip=True) == 'Download']
for link in pdfLinks:
#download
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/513770.html
