1. 用正則表達式斷定郵箱是否輸入正確。php
import re r = "^(\w)+([-+_.]\w+)*@(\w)+((\.\w{2,4}){1,3})$" e = "123-40.5+674_89@vip.sina.com" if re.match(r,e): print(re.match(r, e).group(0)) else: print("error!")
2. 用正則表達式識別出所有電話號碼。html
str = "版權全部:廣州商學院 地址:廣州市黃埔區九龍大道206號" \ "學校學士辦公室:020-82876130 學士招生電話:020-82872773" \ "學校碩士辦公室:020-82876131 碩士招生電話:020-82872774" \ "粵公網安備 44011602000060號 粵ICP備15103669號" numbers = re.findall("(\d{3,4})-(\d{6,8})", str) print(numbers)
3. 用正則表達式進行英文分詞。re.split('',news)正則表達式
news = "Facebook? Informs Data Leak Victims Whether They " \ "Need To Burn Down House, Cut Off Fingerprints, Start Anew," word = re.split("[\s,.?\-]+", news) print(word)
4. 使用正則表達式取得新聞編號api
url = "http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1225/8854.html"
newsId = re.findall("\_(.*).html", url)[0].split("/")[-1]
print(newsId)
5. 生成點擊次數的Request URL函數
Rurl = "http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80".format(newsId)
print(Rurl)
6. 獲取點擊次數url
res = requests.get("http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80".format(newsId))
print(int(res.text.split(".html")[-1].lstrip("('").rsplit("');")[0]))
7. 將456步驟定義成一個函數 def getClickCount(newsUrl):spa
def getClickCount(): url = "http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1225/8854.html" newsId = re.findall("\_(.*).html", url)[0].split("/")[-1] res1 = requests.get("http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80".format(newsId)) return int(res1.text.split(".html")[-1].lstrip("('").rsplit("');")[0]) print(getClickCount())
8. 將獲取新聞詳情的代碼定義成一個函數 def getNewDetail(newsUrl):3d
def getNewDetail(): detail_res = requests.get("http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1225/8854.html") detail_res.encoding = "utf-8" detail_soup = BeautifulSoup(detail_res.text, "html.parser") content = detail_soup.select("#content")[0].text info = detail_soup.select(".show-info")[0].text return content, info print(getNewDetail())
9. 取出一個新聞列表頁的所有新聞 包裝成函數def getListPage(pageUrl):code
def getListPage(): res = requests.get("http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1225/8854.html") res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') for news in soup.select("li"): if (len(news.select('.news-list-info')) > 0): newsUrl = news.select('a')[0].attrs['href'] print(newsUrl) print(getListPage())
10. 獲取總的新聞篇數,算出新聞總頁數包裝成函數def getPageN():orm
def getPageN(): resurl = requests.get("http://news.gzcc.cn/html/xiaoyuanxinwen/") resurl.encoding = "utf-8" soup = BeautifulSoup(resurl.text, 'html.parser') return int(soup.select(".al")[0].text.rstrip("條"))//10+1 print(getPageN())
11. 獲取所有新聞列表頁的所有新聞詳情。
def getall(): for num in range(2,getPageN()): listurl="http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html".format(num) getlist(listurl) getNewDetail(listurl) print(getall())