exceptions & comments

Exception

  • handle errors in python program
  • exit code 0 means program terminated successfully.
try:
    age = int(input('Age: '))
    print(age)
except ValueError:
    print('Invalid value')
try:
    age = int(input('Age: '))
    income = 20000
    risk = income / age
    print(age)
except ZeroDivisionError:
    print('Age can not be 0.')
except ValueError:
    print('Invalid value')

Comments

  • should not explain what a code does
  • use comments to
    • explain why and how
    • explain assunptions
    • remind sth. to be done
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import requests from bs4 import BeautifulSoup from threading import Thread def crawl_books(start, end): session = requests.Session() for i in range(start, end): url = 'http://search.dangdang.com/?key=%BC%C6%CB%E3%BB%FA&act=input&page_index={}'.format(i) try: response = session.get(url, timeout=10) except requests.exceptions.Timeout: print('Timeout occurred when accessing: ' + url) continue page = response.text soup = BeautifulSoup(page, 'lxml') books = soup.find('ul', class_='bigimg') for book in books.find_all('li'): title = book.find('a', class_='pic').get('title') author = book.find('p', class_='search_book_author').text price = book.find('p', class_='price').find('span', class_='search_now_price').text book_link = 'https:' + book.find('a', class_='pic').get('href') try: response = session.get(book_link, timeout=10) except requests.exceptions.Timeout: print('Timeout occurred when accessing: ' + book_link) continue page = response.text soup = BeautifulSoup(page, 'lxml') comment_num_tag = soup.find('a', class_='review_num') if comment_num_tag: comment_num = comment_num_tag.text else: comment_num = '0' print(title, author, price, comment_num) threads = [] for i in range(1, 101, 10): t = Thread(target=crawl_books, args=(i, i+10)) threads.append(t) t.start() for t in threads: t.join()再优化一次,使评论数量能够得到
06-02

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值