1
我正在使用requests
來獲取網頁,例如如下所示。如何獲取從網頁鏈接的JS重定向的pdf
import requests
from bs4 import BeautifulSoup
url = "http://www.ofsted.gov.uk/inspection-reports/find-inspection-report/provider/CARE/EY298883"
r = requests.get(url)
soup = BeautifulSoup(r.text)
對於這些頁面中的每一頁,我希望在標題爲「最新報告」的章節中指出第一個pdf。你怎麼能用美麗的湯做到這一點?
的HTML的相關部分是
<tbody>
<tr>
<th scope="col">Latest reports</th>
<th scope="col" class="date">Inspection <br/>date</th>
<th scope="col" class="date">First<br/>publication<br/>date</th>
</tr>
<tr>
<td><a href="/provider/files/1266031/urn/106428.pdf"><span class="icon pdf">pdf</span> Early years inspection report </a></td>
<td class="date">12 Mar 2009</td>
<td class="date">4 Apr 2009</td>
</tr> </tbody>
下面的代碼看起來像它應該工作,但沒有。
ofstedbase = "http://www.ofsted.gov.uk" for col_header in soup.findAll('th'): if not col_header.contents[0] == "Latest reports": continue for link in col_header.parent.parent.findAll('a'): if 'href' in link.attrs and link['href'].endswith('pdf'): break else: print '"Latest reports" PDF not found' break print '"Latest reports" PDF points at', link['href'] p = requests.get(ofstedbase+link['href']) print p.content break
的問題是,p
包含另一個網頁,而不是PDF它應該。有什麼方法可以得到實際的pdf嗎?
更新:
得到它與任何更好的/更好的解決方案,感激地接受BeautifulSoup
souppage = BeautifulSoup(p.text)
line = souppage.findAll('a',text=re.compile("requested"))[0]
pdf = requests.get(ofstedbase+line['href'])
的一個更迭代工作。