python3----練習題(....)

 # 保存文件(文本,圖片,視頻...)
1
def save_file(): 2 url = 'http://css.8684.cn/citys/images/line/45.jpg' 3 root = r'd:/pics/' 4 path = root + url.split('/')[-1] 5 try: 6 if not os.path.exists(root): 7 os.mkdir(root) 8 if not os.path.exists(path): 9 r = requests.get(url) 10 with open(path, 'wb') as f: 11 f.write(r.content) 12 f.close() 13 print("文件保存成功") 14 else: 15 print("文件已存在") 16 except: 17 print("爬取失敗")

 

 1 # 獲取網頁源碼
 2 
 3 def get_html_text(url):
 4     try:
 5         r = requests.get(url, timeout=30)
 6         r.raise_for_status()   # 若是狀態不是200,引起HTTPError 異常
 7         r.encoding = r.apparent_encoding
 8         return r.text
 9     except:
10         return "產生異常"

 

# 獲取IP
1
def get_ip(): 2 url = 'http://www.ip138.com/ips1388.asp?ip=' 3 ip = '110.242.200.45' 4 try: 5 r = requests.get(url + ip) 6 r.raise_for_status() 7 r.encoding = r.apparent_encoding 8 print(re.findall('<td align="center">(.*?)<br/><br/></td>', r.text)) 9 except: 10 print("爬取失敗")
相關文章
相關標籤/搜索