[英]How to get the URL of an HTML href Attribute containing an .ics file with Python?
我正在尝试从包含.ics
日历的网页上获取.ics
文件的URL。 例如, https://meded.hms.harvard.edu/calendar ,但它适用于任何包含.ics
网页。 以下是我的幼稚尝试(它不会打印任何内容,我也不知道为什么):
import urllib2
import requests
import bs4
def get_ics_url(url):
#page = requests.get('https://meded.hms.harvard.edu/calendar').content
page = requests.get(url).content
soup = bs4.BeautifulSoup(page, 'lxml')
links = soup.find_all('a')
for link in links:
if link.get('href')[-4:]=='.ics':
endout = type(link.get('href'))
print endout
break
我在做什么错,获取我正在寻找的.ics
文件的URL的更好方法是什么?
代码break
将仅在一次迭代后停止脚本,您需要再次缩进该脚本,然后将其放入if
(或使用return
)。 目前,它会打破for
无论什么结果if
是。
第二个问题是,有<a>
元素没有href
属性,这将导致脚本在到达任何.ics链接之前失败:
if link.get('href')[-4:]=='.ics':
TypeError: 'NoneType' object has no attribute '__getitem__'
例如:
<a name="main-content"></a>
<a class="cal-export" title="Note: Past events are not included">Export</a>
您可以通过对link.get('href') != None
链接进行检查来解决此问题,然后再对其执行数组操作。
固定代码:
import urllib2
import requests
import bs4
def get_ics_url(url):
page = requests.get(url).content
soup = bs4.BeautifulSoup(page, 'lxml')
links = soup.find_all('a')
for link in links:
if link.get('href') != None and link.get('href')[-4:]=='.ics':
endout = link.get('href')
return endout
print get_ics_url('https://meded.hms.harvard.edu/calendar')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.