天天看点

Python 爬虫实战: 爬取并下载CSDN文章

目录

        • 1.获取文章对应的标签
        • 2.下载页面
        • 3.提取标题和正文部分
        • 4.提取CSS样式
        • 5.保存网页
        • 6.总结

1.获取文章对应的标签

在文章内容上右击 -> 检查, 找到了

<article>

标签, 该标签的内容就是文章的正文部分。

Python 爬虫实战: 爬取并下载CSDN文章

2.下载页面

使用

requests

库的

get

方法即可, 注意添加

headers

, 否则会爬取不到内容。

requests

库可使用pip安装:

pip install requests --timeout 40

from requests import get
import re,pprint

headers = {
"User-Agent": """Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"""
}

url = input('输入文章网址: ')
req = get(url,headers=headers)
text=req.content.decode('utf-8')
           

3.提取标题和正文部分

需要使用正则表达式。注意: re.S表示点

.

匹配全部字符, 若不用

re.S

参数, 会无法提取内容。

patt=re.compile('<article.*</article>',re.S)
title=re.findall('<title>(.*?)</title>',text,re.S)[0]
content='<html><head><title>%s</title><body>'%title
content += re.findall(patt,text)[0]
           

4.提取CSS样式

CSS样式是修饰网页的工具, 可控制网页的排版。这里再次使用开发工具, 找到了包含CSS样式的标签。如果不用CSS, 可能会出现网页排版混乱的情况。

Python 爬虫实战: 爬取并下载CSDN文章
css_patt=re.compile('<link rel="stylesheet" href=".*?blog.*?" target="_blank" rel="external nofollow" ',re.S)
for css in re.findall(css_patt,text):
    content+=css+'>'
           

5.保存网页

content += '</body></html>'
with open('%s.html'%title,'w',encoding='utf-8') as f:
    f.write(content)
           

6.总结

本程序使用requests库获取网页源代码, 使用re模块提取内容、CSS样式。

注意要多使用Chrome的开发工具。