我想要做的是在Python中找到一個特定的頁面,我的意思是說:例如,如果存在它會輸出它,如果它不,那麼它不會。我知道,但問題是,找到網站頁面的功能是什麼?喜歡。我想查找/測試/,如果它不存在,它會說「/ test /在網站上不存在:test.com」如何在python中查找頁面?
我該怎麼辦?
我想要做的是在Python中找到一個特定的頁面,我的意思是說:例如,如果存在它會輸出它,如果它不,那麼它不會。我知道,但問題是,找到網站頁面的功能是什麼?喜歡。我想查找/測試/,如果它不存在,它會說「/ test /在網站上不存在:test.com」如何在python中查找頁面?
我該怎麼辦?
只需檢查頁面的HTTP status code。例如,使用requests:
>>> import requests
>>> response = requests.get('http://google.com/test')
>>> response.status_code
404
>>> if response.status_code == 404:
... print "/test/ does not exist on the website: google.com"
...
/test/ does not exist on the website: google.com
如果使用類似requests
的庫,則可以簡單地嘗試一下url。如果它返回一個404,那麼該頁面不存在。
E.g.
r = requests.get('http://test.com/test')
if r.status_code == 404:
print "/test/ does not exist on the website: test.com"
您還可以使用內置的urllib模塊
from urllib import urlopen
response = urlopen('http://stackoverflow.com/questions/17993222/how-do-i-find-a-page-in-python')
if response.getcode() == 200:
print("page exists")
elif response.getcode() == 404:
print("page does not exist")
你嘗試過什麼?提示:嘗試下載頁面並檢查它是否成功。 – mnagel
我不希望它下載頁面,我只是想'嘗試:'在python中查找頁面。 –