python爬虫代码更新

Posted qq_22426297

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python爬虫代码更新相关的知识,希望对你有一定的参考价值。

昨天和室友看《Python 金融大数据挖掘与分析全流程详解》第67,68页的代码时,发现网页已经更新了,代码运行错误。

先看结果,

大致由三部分组成,标题,时间,和链接。

打开爬虫的网页

 

缺个链接,按f12,打开开发者工具

 

在开发者工具上面出现这个网页代码,这个截图结果可能在网页右边,也可能在下面

这样大家都发现了,链接和标题都有了,可以写正则

p_href = '<h3 class=".*?"><a href="(.*?)"'
href = re.findall(p_href, res, re.S)
p_title = '<h3 class=".*?">.*?>(.*?)</a>'
title = re.findall(p_title, res, re.S)

还剩下时间和作者,继续按照上面的方式查找

这样一来,就发现了作者和时间继续正则

p_info = '<span class="c-color-gray.*?">(.*?)</span>'
info = re.findall(p_info, res, re.S)

最后再上完整代码,

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'
url = 'https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&word=阿里巴巴&x_bfe_rqs=03E80&x_bfe_tjscore=0.596217&tngroupname=organic_news&newVideo=12&rsv_dl=news_b_pn&pn=20'
res = requests.get(url, headers=headers).text
# https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&word=阿里巴巴&x_bfe_rqs=03E80&x_bfe_tjscore=0.596217&tngroupname=organic_news&newVideo=12&rsv_dl=news_b_pn&pn=20
p_info = '<span class="c-color-gray.*?">(.*?)</span>'
info = re.findall(p_info, res, re.S)
p_href = '<h3 class=".*?"><a href="(.*?)"'
href = re.findall(p_href, res, re.S)
p_title = '<h3 class=".*?">.*?>(.*?)</a>'
title = re.findall(p_title, res, re.S)
source = []
date = []
for i in range(len(title)):
    title[i] = title[i].strip()
    title[i] = re.sub('<.*?>', '', title[i])
    info[i] = re.sub('<.*?>', '', info[i])
    source.append(info[2*i])
    date.append(info[2*i+1])
    source[i] = source[i].strip()
    date[i] = date[i].strip()
    print(str(i + 1) + '.' + title[i] + '(' + date[i] + '-' + source[i] + ')')
    print(href[i])

在最后,希望大家不要照搬书本,自己好好分析,打好基础,加油。

以上是关于python爬虫代码更新的主要内容,如果未能解决你的问题,请参考以下文章

python帮室友避险——爬虫加可视化

背着室友用Python在宿舍兼职接单3天赚了一千块,实现生活费自由,室友都羡慕哭了

背着室友用Python在宿舍兼职接单3天赚了一千块,实现生活费自由,室友都羡慕哭了

《 始祖研究自然,爬虫研究书本。》 回复

python 有没有smbinning

为啥我的python爬虫界面与博主不一样