【发布时间】:2021-06-09 09:17:57
【问题描述】:
我从未使用过网络抓取,但现在我认为这是唯一可以帮助我完成我想做的事情的方法。所以我在互联网上查看了一个示例代码。 StackOverflow 上这个公认的答案似乎是我正在寻找的答案:Download all pdf files from a website using Python
这不起作用,并且给了我一个“403 禁止错误”,因为正如 @andrej Kesely 所说:我必须指定用户代理
然后我在他回答后更新了问题:
import os
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup
# an example of a working url
#url = "http://www.gatsby.ucl.ac.uk/teaching/courses/ml1-2016.html"
# my url (still not working)
url = 'http://www.covidmaroc.ma/Pages/LESINFOAR.aspx'
#You can use http://httpbin.org/get to see User-Agent in your browser. mine is
headers = {'User-Agent': 'Mozilla/5.0'} #Mozilla/5.0 #Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36"'}
#If there is no such folder, the script will create one automatically
folder_location = 'webscraping'
if not os.path.exists(folder_location):os.mkdir(folder_location)
soup = BeautifulSoup(requests.get(url, headers=headers).content, 'html.parser')
for a in soup.select("a[href$='.pdf']"):
filename = os.path.join(folder_location,a['href'].split('/')[-1])
with open(filename, 'wb') as f:
f.write(requests.get(urljoin(url,a['href'])).content)
现在它可以正常工作并创建 PDF 文件。但是当我尝试打开任何 PDF 文件时,它无法在我拥有的任何 pdf 阅读器中打开,即使在 chrome 中,它也会显示“错误:无法加载 pdf 文档”。此外,抓取的 PDF 只有 179 字节,而“手动”下载的 PDF 为 1.XX Mb
【问题讨论】:
标签: python-3.x web-scraping beautifulsoup