这样试试(追加模式):
import requests
import re
import time
key = 'Python' # 设置搜索的关键词
url = 'https://yq.aliyun.com/search/articles/'
data = requests.get(url, params={'q': key}).text # 拿到第一页的源码
pat1 = '<div class="_search-info">找到(.*?)条关于'
allline = re.compile(pat1, re.S).findall(data)[0] # 正则匹配
allpage = int(allline) // 15 + 1 # 获取总页码
for i in range(0, int(allpage)):
print('---------------正在爬第{}页'.format(i + 1))
index = str(i + 1) # 页码下标
getdata = {'q': key, 'p': index, } # 依次获取页数
data = requests.get(url, params=getdata).text # 获取这一页的源码
pat_url = '<div class="media-body text-overflow>.*?<a "href=(.*?)"'
articles = re.compile(pat_url, re.S).findall(data) # 正则匹配这一页的内容
for j in articles:
thisurl = "https://yq.aliyun.com" + j
thisdata = requests.get(thisurl).text
pat_title = '<p class="hiddenTitle">(.*?)</p>'
pat_content = "<div class='content-detail markdown-boby'>(.*?)<div class="">"
title = re.compile(pat_title, re.S).findall(thisdata)[0]
content = re.compile(pat_content, re.S).findall(thisdata)[0]
fh = open("D:\\Captures\\p\\" + str(i + 1) + '_' + str(time.time()) + '.html', 'a',
encoding='utf-8')
fh.write(title + '<br /><br />' + content)
fh.close()
|