[英]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.