Python爬虫学习之正则表达式爬取个人博客

时间:2023-03-09 16:28:33
Python爬虫学习之正则表达式爬取个人博客

实例需求:运用python语言爬取http://www.eastmountyxz.com/个人博客的基本信息,包括网页标题,网页所有图片的url,网页文章的url、标题以及摘要。

实例环境:python3.7
       requests库(内置的python库,无需手动安装)
       re库(内置的python库,无需手动安装)

实例网站:

  第一步,点击网站地址http://www.eastmountyxz.com/,查看页面有哪些信息,网页标题、图片以及摘要等

     Python爬虫学习之正则表达式爬取个人博客

  第二步,查看网页源代码,即可看到想要爬取的基本信息

   Python爬虫学习之正则表达式爬取个人博客

  Python爬虫学习之正则表达式爬取个人博客

实例代码:

 #encoding:utf-8
import re
#import urllib.request
import requests def getHtmlStr(url):
#content = urllib.request.urlopen(url).read().decode("utf-8")
res = requests.get(url)
res.encoding = res.apparent_encoding
return res.text def parseHtml(content):
#爬取整个网页的标题
title = re.findall(r'<title>(.*?)</title>', content)
print(title[0])
#爬取图片地址
urls = re.findall(r'<img .*src="\./(.*?)"', content)
baseUrl = 'http://www.eastmountyxz.com/' for i in range(len(urls)):
urls[i] = baseUrl + urls[i]
print(urls) #爬取文章信息
p = r'<div class="essay.*?">(.*?)</div>'
artcles = re.findall(p, content, re.S)
for a in artcles:
res = r'<a .*href="(.*?)">'
t1 = re.findall(res, a, re.S) #超链接
print(t1[0])
t2 = re.findall(r'<a .*?>(.*?)</a>', a, re.S) #标题
print(t2[0])
t3 = re.findall('<p style=.*?>(.*?)</p>', a, re.S) #摘要(
print(t3[0].replace(' ',''))
print('') if __name__ == '__main__':
url = "http://www.eastmountyxz.com/"
htmlString = getHtmlStr(url)
parseHtml(htmlString)

实例结果:

    Python爬虫学习之正则表达式爬取个人博客