Python网络爬虫实战4:通过新浪财经来挖掘中国互联网公司热门信息

代码示例

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 + '新浪财经信息获取失败')

运行结果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

简时刻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值