爬取东方财富网文章标题和正文并保存的代码。自己知道写的很烂,不过主要是为了自己备忘,也为了以后回头看看自己的烂作品,哈哈哈。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
import time
#实现根据url进行网页爬取,并得到想要的文本信息,保存在一个文件列表txtlist中。
def gethtml(url,deep,txtlist):
try:
for i in range(deep):
print('>>>>>',deep-i)
r = requests.get(url + str(i + 1), timeout=30)
if r.status_code == 200:
r.encoding = r.apparent_encoding
r.raise_for_status()
soup = BeautifulSoup(r.text,'html.parser')
a = soup.find_all('p',class_='title')
for b in a:
c = b.find_all('a')
print(c[0].text,c[0]['href'])
#将爬取的文章标题和正文链接添加进txtlist变量中
txtlist.append('>>>>>>>'+c[0].text+c[0]['href']+'\n')
#通过request将正文链接进入正文,爬取正文。
r1 = requests.get(c[0]['href'], timeout=30)
r1.raise_for_status()
r1.encoding = r1.apparent_encoding
soup1 = BeautifulSoup(r1.text, 'html.parser')
a1 = soup1.find_all('div', id='ContentBody')
# print(a)
for b1 in a1:
c1 = b1.find_all('p')
for e1 in c1:
print(e1.text)
#将每篇的正文再次赋予txtlist变量
txtlist.append(e1.text)
i += 1
except:
print('有错误发生')
return
#将txtlist列表中的数据保存到E盘111.txt文件中。
def savefile(txt):
try:
with open('e:111.txt', 'a', encoding='utf-8') as f:
timenow = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
print(timenow)
f.write('>>文章爬取时间>>' + timenow + '>>>>>>>' + txt + '\n')
except:
print('有错误未能存盘')
return
#调用的主函数
def main():
deep = 2 #定义要抓取多少层页面
url = 'http://finance.eastmoney.com/news/cdfsd.html'
txtlist = []
gethtml(url,deep,txtlist)
txt = ''.join(txtlist) #将列表文件变成字符串文件,便于进行保存。
print(txt)
savefile(txt)
main()