爬蟲也是程式, 所以它是很笨的, 只會按照人寫的腳本去行動, 因此在寫爬蟲的時候要記得去處理可能發生的例外情形, 不然你的蟲爬沒幾下就可能會罷工或是做出預料之外的行為.
import requests
from bs4 import BeautifulSoup
def main():
url = 'http://blog.castman.net/web-crawler-tutorial/ch1/connect.html'
h1 = get_header_text(url, 'h1')
if h1:
print('h1: ' + h1)
h2 = get_header_text(url, 'h2')
if h2:
print('h2: ' + h2)
p = get_header_text(url, 'p')
if p:
print('p: ' + p)
def get_header_text(url, header_tag):
try:
resp = requests.get(url)
if resp.status_code == 200:
soup = BeautifulSoup(resp.text, 'html.parser')
return soup.find(header_tag).text
except Exception as exception:
return None
if __name__ == '__main__':
main()
在get_header_text中, 會把取得response的過程放在try...except區塊之中, 所以爬蟲如果無法正常取得response的時候, 就會回傳None, 而後續處理的程式也會知道這時候沒東西, 就不進行任何處理了.