import requests
import bs4
import re
def open_url(url):
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'}
res = requests.get(url, headers=headers)
return res
def find_title(res):
soup = bs4.BeautifulSoup(res.text,'html.parser')
#文章标题
title = []
targets = soup.find_all('p',class_='topic-summary')
for each in targets:
title.append(each.a.text.strip('\n').strip(' '))
#资料(作者,类型,时间)
messages = []
targets = soup.find_all('p',class_='topic-info')
for each in targets:
messages.append([each.a.text ,re.search(r"(\d{4}-\d{1,2}-\d{1,2})",each.text).group()])
result = []
length = len(title)
for i in range(length):
result.append([title[i],messages[i]])
return result
#找出一共多少页
def find_depth(res):
soup = bs4.BeautifulSoup(res.text, 'html.parser')
depth = soup.select('#Wrapper > div > div.span10 > div > div > div.pagination.clearfix > ul > li:nth-child(2) > a')
depth = re.search('\d{3}',str(depth))
return int(depth.group())
def main():
res = "https://xz.aliyun.com/"
res1 = open_url(res)
depth = find_depth(res1)
result = []
for i in range(1,depth):
url = res + '/?page=' + str(2 * i)
print('正在爬取第',i,'页')
res2 = open_url(url)
result.extend(find_title(res2))
with open("先知.txt",'w',encoding='utf-8') as file:
for each in result:
file.write(str(each))
file.write('\n')
file.write('=============================================')
file.write('\n')
if __name__ == "__main__":
main()
代码已改好 |