好几个月没写博文了,有空来玩玩爬虫,之前接触了一个爬虫的项目,感触挺深的,当时有个爬取巨潮网的操作,网上的代码天花乱坠,最后还是要靠自己,今天这篇算是入门级别,欢迎收藏评论。🐳🐳🐳🐳🐳

按默认顺序

效果

在这里插入图片描述

代码

import requests
import re

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'}

url = 'http://www.baidu.com/s?tn=news&rtt=1&bsst=1&cl=2&wd=阿里巴巴'  # 把链接中rtt参数换成4即是按时间排序,默认为1按焦点排序,3.4.1小节也有讲到
res = requests.get(url, headers=headers).text  # 加上headers用来告诉网站这是通过一个浏览器进行的访问
# 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 c-gap-right-xsmall" .*?>(.*?)</span>'
date = re.findall(p_date, res)
p_source = '<span class="c-color-gray" .*?>(.*?)</span>'
source = re.findall(p_source, res)

# print(title)
# print(href)
# print(date)
# print(source)
#
for i in range(len(title)):  # range(len(title)),这里因为知道len(title) = 10,所以也可以写成for i in range(10)
    title[i] = title[i].strip()  # strip()函数用来取消字符串两端的换行或者空格,不过目前(2020-10)并没有换行或空格,所以其实不写这一行也没事
    title[i] = re.sub('<.*?>', '', title[i])  # 核心,用re.sub()函数来替换不重要的内容
    print(str(i + 1) + '.' + title[i] + '(' + source[i] + ' ' + date[i] + ')')
    print(href[i])

解析

重点就是了解正则表达式规则,理解非贪婪匹配和贪婪匹配,还有就是换行问题的考虑。数据清洗:理解sub()函数和strip()函数即可。

按时间顺序爬取

爬虫的重点就是——网址一定要对上,一定是先要有对应的网址,然后再去进行后续的操作,如果网址都不对,那么后面就一定不对,做爬虫最重要的就是观察网址的变化

以爬取腾讯新闻为例,默认的网址:

http://www.baidu.com/s?tn=news&rtt=1&bsst=1&cl=2&wd=‘腾讯’

在这里插入图片描述

默认是按照焦点排序,这里选择时间排序

在这里插入图片描述

https://www.baidu.com/s?tn=news&rtt=4&bsst=1&cl=2&wd=‘腾讯’

可以看到,它们唯一的区别就在于“rtt”后的数字,推断:rtt=4按照时间;rtt=1按照焦点排序,故将上述代码的url中的rtt修改为4即可。

在这里插入图片描述
可以看到已经按照时间排序

一次性批量爬取多页内容

上面讲到了观察,那么这里要学的就是“变通”,会玩url地址的人或者对url敏感的人学爬虫一般都非常厉害。🐻‍❄️🐻‍❄️🐻‍❄️🐻‍❄️🐻‍❄️

默认时候的网址:

https://www.baidu.com/s?tn=news&rtt=4&bsst=1&cl=2&wd=%E8%85%BE%E8%AE%AF&x_bfe_rqs=032000000000000000000000000000000000000000000008&x_bfe_tjscore=0.080000&tngroupname=organic_news&newVideo=12&goods_entry_switch=1&rsv_dl=news_b_pn&pn=0
😶‍🌫️😶‍🌫️😶‍🌫️删除掉一些内容并做一些处理
https://www.baidu.com/s?tn=news&rtt=4&bsst=1&cl=2&wd=‘腾讯’&pn=0
爬取第2页:
https://www.baidu.com/s?tn=news&rtt=4&bsst=1&cl=2&wd=‘腾讯’&pn=10
爬取第3页:
https://www.baidu.com/s?tn=news&rtt=4&bsst=1&cl=2&wd=‘腾讯’&pn=20
💡💡💡规律
pn按照10、20、30…这样的规律递增:
num = (page - 1) * 10

修改代码

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(page):
    num = (page - 1) * 10  # 参数规律是(页数-1)*10
    url = 'http://www.baidu.com/s?tn=news&rtt=4&bsst=1&cl=2&wd=阿里巴巴&pn=' + str(num)
    res = requests.get(url, headers=headers).text
    # 其他相关爬虫代码

    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 c-gap-right-xsmall" .*?>(.*?)</span>'
    date = re.findall(p_date, res)
    p_source = '<span class="c-color-gray" .*?>(.*?)</span>'
    source = re.findall(p_source, res)
    print("**********title len is {} ".format(len(title)))
    print("**********date len is {}".format(len(date)))
    print("**********source len is {}".format(len(source)))
    for i in range(len(date)):  
        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])


for i in range(3):  # 这里一共爬取了3页
    baidu(i+1)  # i是从0开始的序号,所以要写成i+1表示第几页
    print('第' + str(i+1) + '页爬取成功')  # i是从0开始的序号,所以写i+1
    time.sleep(3)  # 不要爬太快,爬太快会被百度反爬

效果图

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

爬取多家公司多页数据

修改代码

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, page):
    num = (page - 1) * 10  # 参数规律是(页数-1)*10
    url = 'http://www.baidu.com/s?tn=news&rtt=4&bsst=1&cl=2&wd=' + company + '&pn=' + str(num)
    res = requests.get(url, headers=headers).text

    # 正则表达式提取内容
    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 c-gap-right-xsmall" .*?>(.*?)</span>'
    date = re.findall(p_date, res)
    p_source = '<span class="c-color-gray" .*?>(.*?)</span>'
    source = re.findall(p_source, res)

    for i in range(len(date)):  # range(len(title)),这里因为知道len(title) = 10,所以也可以写成for i in range(10)
        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])


companys = ['阿里巴巴', '万科集团', '百度集团', '腾讯', '京东']
for company in companys:
    for i in range(3):  # 这里一共爬取了3页
        baidu(company, i+1)  # i是从0开始的序号,所以要写成i+1表示第几页
        print(company + '第' + str(i+1) + '页爬取成功')  # i是从0开始的序号,所以写i+1
        time.sleep(3)  # 不要爬太快,爬太快会被百度反爬

效果图(部分)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

后面不再赘述🖌️🖌️🖌️

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐