我试着用下面的代码从链接中下载所有的pdf文件,但是每次运行这些代码时它都会下载所有的文件。建议:第一次应该下载所有的pdf,从下一次应该只下载哪一个是新的。(应该先检查哪一个是新的) 我的代码:
import requests
from bs4 import BeautifulSoup
root_url = 'https://www.iea.org'
def getLinks(url):
all_links = []
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
for href in soup.find_all(class_='omrlist'):
all_links.append(root_url + href.find('a').get('href'))
return all_links
yearLinks = getLinks(root_url +'/oilmarketreport/reports/')
# get report URL
reportLinks = []
for url in yearLinks:
links = getLinks(url)
#reportLinks.extend(links)
#print(reportLinks)
i =0
for url_ in links:
if "AnnualStatisticalSupplement" not in url_:
url__ = url_.replace("org..", "org").replace("../", "")
response = requests.get(url__, stream=True)
lastindex= url__.rfind('/')
strlen = len(url__)
filename = url__[lastindex:strlen]
with open('/home/pdfs/'+ str(filename), 'wb') as pdffile:
pdffile.write(response.content)
i += 1
print(url__)
print("Download Completed")
然后我需要存储的文件是mongodb,我应该如何做到这一点,使三列(pdf名称,报告日期,进程标志)。你知道吗
很抱歉您的代码发生了重大变化。因为你的代码太乱了。 如果您想下载一段时间以来没有的pdf,您必须添加
if-loop
来控制您的操作。顺便说一下,如果您将页面url添加到数据库中,则无需再访问一次即可获得pdf名称。你知道吗相关问题 更多 >
编程相关推荐