import urllib.request #导入模块,用于网页访问 |
import re #导入文本正则模块,用于取中间文本 |
#获取网页源码 |
url = 'https://mbd.baidu.com/newspage/data/landingsuper?context=%7B%22nid%22%3A%22news_9958850143698636667%22%7D&n_type=0&p_from=1' #要访问的网页 |
a = urllib.request.urlopen(url) #打开网页 |
html = a.read() #获取网页源码 |
html = html.decode() #编码转换 |
#取文本标题 |
title = re. compile ( "<title>" + "(.*?)" + "</title>" ,re.S ).findall(html) #取中间文本 用于取中间的文本,得到集合 |
print ( "标题:" ,title[ 0 ]) #获取集合第一个元素 |
#获取作者名称 |
title = re. compile ( '<p class="author-name">' + "(.*?)" + '</p><div class="article-source' ,re.S ).findall(html) #取中间文本 用于取中间的文本,得到集合 |
print ( "作者:" ,title[ 0 ]) #获取集合第一个元素 |
#获取正文 |
titles = re. compile ( '<span class="bjh-p">' + "(.*?)" + '</span></p><p>' ,re.S ).findall(html) #取中间文本 用于取中间的文本,得到集合 |
for title in titles : |
print (title) #获取集合所有元素 |