使用正規表示式,取得點選次數,函式抽離

2022-06-04 04:36:09 字數 3267 閱讀 4510

1. 用正規表示式判定郵箱是否輸入正確。

importre 

defvalidateemail(email):

if len(email) > 7:

if re.match("

^.+\\@(\\[?)[a-za-z0-9\\-\\.]+\\.([a-za-z]|[0-9])(\\]?)$

", email) !=none:

print('

good')

#return 1

#return 0

print('

exit')

validateemail(

'[email protected]

')

2. 用正規表示式識別出全部**號碼。

import

re

text="

(021)88776543 010-55667890 02584533622 057184720483 837922740

"m=re.findall(r"

\(?0\d[) -]?\d

",text)

ifm:

print

m else

:

print

'not match

'

3. 用正規表示式進行英文分詞。re.split('',news)

importre#

不保留匹配項

m = re.split('

\d+' , '

123abc321cba')

print

mprint"\n

"#保留匹配項

m = re.split('

(\d+)

' , '

123abc321cba')

print m

4. 使用正規表示式取得新聞編號

5. 生成點選次數的request url

6. 獲取點選次數

7. 將456步驟定義成乙個函式 def getclickcount(newsurl):

8. 將獲取新聞詳情的**定義成乙個函式 def getnewdetail(newsurl):

import

requests

from bs4 import

beautifulsoup

from datetime import

datetime

import

reres = requests.get('

')res.encoding = '

utf-8

'soup = beautifulsoup(res.text, '

html.parser')

#獲取新聞點選次數

defgetnewsid(url):

newsid = re.findall(r'

\_(.*).html

', url)[0][-4:]

clickurl = '

'.format(newsid)

clickres =requests.get(clickurl)

#利用正規表示式獲取新聞點選次數

clickcount = int(re.search("

hits'\).html\('(.*)'\);

", clickres.text).group(1))

return

clickcount

defgetnewdetail(newsurl):

#讀取新聞細節

resdescript =requests.get(newsurl)

resdescript.encoding = "

utf-8

"soupdescript = beautifulsoup(resdescript.text, '

html.parser')

content = soupdescript.select("

.show-content

")[0].text #

正文 info = soupdescript.select("

.show-info

")[0].text #

#第一種方法 分離 message = info.split()

#第二種方法 用正規表示式

time = re.search("

", info).group(1)

author = re.search("

", info).group(1)

right = re.search("

", info).group(1)

resource = re.search('

', info).group(1)

video = re.search("

攝影:(.*)\xa0\xa0\xa0\xa0點選:

", info).group(1)

count =getnewsid(newsurl)

datetime = datetime.strptime(time, '

%y-%m-%d %h:%m:%s')

print('

標題' + '

: ' +title)

print('

概要' + '

: ' +description)

print('

鏈結' + '

: ' +a)

print('

正文' + '

:' +content)

print('

'.format(datetime, author, right, resource, video,count))

print("\n"

)for s in soup.select("li"

):

if len(s.select("

.news-list-title

"))>0:

title = s.select("

.news-list-title

")[0].text #

新聞標題

description = s.select("

.news-list-description

")[0].text #

新聞描述

a = s.a.attrs["

href

"] #

**新聞細節

getnewdetail(a)

使用正規表示式,取得點選次數,函式抽離

學會使用正規表示式 1.用正規表示式判定郵箱是否輸入正確。r w w w w e 67890222 qq.com if re.match r,e print re.match r,e group 0 else print 非郵箱格式!2.用正規表示式識別出全部 號碼。3.用正規表示式進行英文分詞。r...

使用正規表示式,取得點選次數,函式抽離

1.用正規表示式判定郵箱是否輸入正確 r w w w w e 123456789 qq.com if re.match r,e print re.match r,e group 0 else print error 2.用正規表示式識別出全部 號碼。str 羅德廣的號碼020 123456,藝術大師...

使用正規表示式,取得點選次數,函式抽離

1.用正規表示式判定郵箱是否輸入正確。r w w w w e 157049540 qq.com if re.match r,e print suc else print false 2.用正規表示式識別出全部 號碼。a re.findall d d str print a 3.用正規表示式進行英文分...