这个示例刚好可以把最近学到的requests库和argparse库结合在一起,算是对知识点的一个巩固吧。
# website_text_spider.py
# created on 20th April 2019
'''
This will print the website information text[:1000]
once you pass the website url.
'''
__author__ = 'TeddyLiu95'
__version__ = '1.0'
# 导入模块
import requests
import argparse
def spider(url):
# 由于种种原因可能会出现无法获取url内容的情况,所以最好是用上try,except.
try:
r = requests.get(url)
# r.raise_for_status()表示在返回200的时候则代码正常运行,若非200,则执行except的内容。
r.raise_for_status()
# 将编码方式换为正文可读的编码方式。
r.encoding = r.apparent_encoding
# 如果直接打印r.text全文的话,会由于内容过多导致运行速度减慢,所以只取0到999个字节。
print(r.text[:1000])
except:
print('爬取失败')
def get_parser():
parser = argparse.ArgumentParser(description='To get web information by url')
parser.add_argument('url', type=str, nargs=1, help='web url')
return parser
def main():
parser