首先在這裏向大家推薦,極客學院,好不好,用了才知道。
博客,算是我學習各種IT知識之後的一個總結,CSDN上的大神的博客,讓我受益良多,除此之外,還有博客園、腳本之家等等很多的好網站。當然腳本之家的廣告着實多了點。而極客學院是我最近一個月纔有瞭解的網站,開始時,自己去註冊個號,結果悲劇了,只有3天的使用期限,我可是綁定了手機號的,你纔給我三天時間,坑啊。然後一次一個人在羣裏發鏈接,點進去送了我一個月,後來我才知道,原來邀請送時間的,後來一個月變成一年了,哈哈,然後在這段時間,學了好多東西,python就是其中之一。
嘮叨了有點多,進入正題。
一.工具:
1.基本的python環境
2.requests 這個類庫要裝上
3.pycharm 開發環境。
4.強調一下,所有操作均在windows操作系統上,小弟沒錢用不起高大上的Mac(要給我打錢的,可留言,^_^)
二、需要掌握的知識
1.python基礎知識。去學 極客學院
2.正則表達式 基礎不瞭解的,去學。正則表達式
三、代碼分析
#coding = utf-8
import requests
import re
import sys
import os
from os.path import join,getsize
reload(sys)
sys.setdefaultencoding('utf8');
header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36'}
html = requests.get('http://www.dy2018.com/')
html.encoding='gbk'
# print html.text
filehandler = open('F:/document/python/python_dy2018.com.txt', 'wb+')
i=0;
html2 = requests.get('http://www.dy2018.com/')
html2.encoding='gbk'
target = re.findall('<div class="title_all">(.*?)</div>',html2.text,re.S)
for each in target:
# print each
content = re.findall('<div class="co_(.*?)</div>',html2.text,re.S)
for each1 in content:
a = re.findall('<a href=\'(.*?)\'',html2.text,re.S)
for each1 in a:
url = 'http://www.dy2018.com/'+each1
htmlChild =requests.get(url)
htmlChild.encoding='gbk'
lianjie = re.findall('bgcolor="#fdfddf"><a href="(.*?)">ftp',htmlChild.text,re.S);
title = re.findall('bgcolor="#fdfddf"><a href="(.*?)">ftp',htmlChild.text,re.S);
for eachtitle1 in title:
file = open('F:/document/python/'+str(i)+'.txt','wb+')
print eachtitle1
for eachtitle in lianjie:
print eachtitle
file.write(eachtitle+'\n')
i+=1
# eachtitle1 = re.findall('(.*?)',eachtitle,re.S)
# for eachtileChild in eachtitle1:
# print eachtileChild
代碼大體是這樣,寫得不好望大家見諒。1.導入相應的類庫
requests
re 正則表達式
sys 這個的作用是防止亂碼
2.requests.get(url) 取得該地址網頁的源碼
3.html.encoding='gbk' 因爲網站用的是gbk 所以要保持一致,否則又亂碼
4. open() 方法用來操作文件,詳情點擊
5.re.findall() 利用正則表達式 搜索你需要的信息
6.print 方法。合理使用這個方法可以讓你開發的更加便捷。當然用pycharm的斷點調試也可以。
效果圖: