代码示例
import requests
import re
# 用户代理设置
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 new(company):
url = 'https://search.sina.com.cn/?q=' + company + '&range=all&c=news&sort=time&ie=utf-8'
res = requests.get(url, headers=headers, timeout=10).text
# print(res)
p_title = '<h2><a href=".*?" target="_blank">(.*?)</a>'
title = re.findall(p_title, res, re.S) # 注意偶尔有的地方有换行,所以得加re.S(标题和链接其实不加也没事,主要是date得加)
p_href = '<h2><a href="(.*?)" target="_blank">'
href = re.findall(p_href, res, re.S)
p_date = '<span class="fgray_time">(.*?)</span>'
date = re.findall(p_date, res, re.S)
for i in range(len(title)):
title[i] = re.sub('<.*?>', '', title[i])
date[i] = date[i].split(' ')[1] # 获取来源的话,把[1]换成[0]就是来源了,如果有换行,通过strip()函数处理即可
print(str(i + 1) + '.' + title[i] + ' - ' + date[i])
print(href[i])
companys = ['百度', '华为', '小米', '腾讯', '阿里巴巴', '京东']
for i in companys:
try: # 异常处理判断,如果成功输出try中的内容;失败则输出except中的内容
new(i)
print(i + '新浪财经信息获取成功')
except:
print(i + '新浪财经信息获取失败')
运行结果


