python 爬取博客

import requests
import re


url='https://blog.csdn.net/maosijunzi/article/details/79988540'
header = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) '
                         'Chrome/48.0.2564.116 Safari/537.36',
           'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
           'Accept-Encoding': 'gzip', 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4'
}


def getHtml(url):
    conn = requests.session()
    html=conn.get(url, headers=header)
    print(html.text)
    return html.text


def getContent():
    html=getHtml(url)
    title_article = re.findall("

(.*)

"
, html) print("标题:", title_article[0]) title_time = re.findall("(.*)", html) print("时间:", title_time[0]) content = re.findall("
(.*?), html, re.M | re.S) content = str(content[0]) content = content.replace("<", "<") content = content.replace(">", ">") content = content.replace("\\n", "
"
) content = content.replace("\\t", " ") print('内容:', content) file=open(str(title_article[0]) + '.html', 'w+') file.write(str(title_article[0]) + '
'
) file.write(str(title_time[0]) + '
'
) file.write(str(content) + '\n') file.close() getContent()

你可能感兴趣的:(python)