我使用requests
来获取网页,例如如下所示。
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的相关部分是
^{pr2}$下面的代码看起来应该可以工作,但是不行。
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文件吗?
更新:
让它在beauthulsoup的另一个迭代中工作
souppage = BeautifulSoup(p.text)
line = souppage.findAll('a',text=re.compile("requested"))[0]
pdf = requests.get(ofstedbase+line['href'])
如有更好/更好的解决方案,我们将不胜感激。
让它在beauthulsoup的另一个迭代中工作
这不是最干净的解决方案,但是您可以遍历列标题,直到找到“最新报告”,然后在该表中搜索指向PDF文件的第一个链接。在
您可以尝试使用Selenium WebDriver(
^{pr2}$python -m "easy_install" selenium
)自动指示Firefox下载该文件。这需要Firefox:这个解决方案非常强大,因为它可以做任何人类用户可以做的事情,但它也有缺点。例如,我试图解决Firefox提示下载的问题,但它对我不起作用。结果可能会因安装的附加组件和Firefox版本而异。在
相关问题 更多 >
编程相关推荐