我试图从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下的标签‘每月关键指标’只。请建议对代码进行必要的修改。
发布于 2022-10-07 12:04:42
您可以尝试缩小选择链接的选项卡。选项卡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']")但是你不是在用每个报告下载相同的3x文件吗?您可以将for-循环更改为只从以" download“作为文本的链接中下载:
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:
#downloadhttps://stackoverflow.com/questions/73985919
复制相似问题