异常处理
companys = ['华能信托','阿里巴巴','百度','京东']
for i in companys:
try:
baidu(i)
print(i+'爬取成功')
except:
print(i+'爬取失败')
如果出现异常,没有写异常处理的话就会直接终止整个程序的运行,而加上就会执行except后的操作,不会完全终止跳出。
24小时实时爬虫实战
要想实现24小时不断爬取,只需要加一个
while True:
如果不需要不间断地运行,而是每隔一定时间运行一次,可以用time库,然后使用time.sleep()函数来达到目的
加上一个
time.sleep(1024)
表示爬取一次休息1024秒
while True: # 一直运行的意思
companys = ['华能信托', '阿里巴巴', '百度', '京东']
for i in companys:
try:
baidu(i)
print(i + '爬取成功')
except:
print(i + '爬取失败')
time.sleep(1024) # 每1024秒运行一次
实战完整代码:
import requests
import re
import time
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'}
def baidu(company):
url = 'https://www.baidu.com/s?tn=news&rtt=1&bsst=1&cl=2&wd=' + company
res = requests.get(url, headers=headers).text
# print(res)
p_href = '<h3 class="news-title_1YtI1"><a href="(.*?)"'
href = re.findall(p_href, res, re.S)
p_title = '<h3 class="news-title_1YtI1">.*?>(.*?)</a>'
title = re.findall(p_title, res, re.S)
p_date = '<span class="c-color-gray2 c-font-normal">(.*?)</span>'
date = re.findall(p_date, res)
p_source = '<span class="c-color-gray c-font-normal c-gap-right">(.*?)</span>'
source = re.findall(p_source, res)
for i in range(len(title)):
title[i] = title[i].strip() # strip()函数用来取消字符串两端的换行或者空格
title[i] = re.sub('<.*?>', '', title[i]) # 核心,用re.sub()函数来替换不重要的内容
print(str(i + 1) + '.' + title[i] + '(' + date[i] + '-' + source[i] + ')')
print(href[i])
while True: # 一直运行的意思
companys = ['华能信托', '阿里巴巴', '百度', '京东']
for i in companys:
try:
baidu(i)
print(i + '爬取成功')
except:
print(i + '爬取失败')
time.sleep(1024) # 每1024秒运行一次
这样爬取的有一个缺点:会出现重复信息,如何去重将在后面讲解。