爬虫的操作

2023-11-11

目录

爬虫基本 + re/etree/beautifulsoup+保存本地/连接数据库

基本

re

lxml/etree

beautifulsoup

保存到本地

传入数据库


大致分为

爬虫基本 + re/etree/beautifulsoup+保存本地/连接数据库

基本

爬一个很简单的百度新闻热搜

爬排名 热搜名 和热搜指数

百度热搜

 

我们直接开始分析

其实这个页面很简单 就是在自己页面的源代码上

也不需要什么分析直接爬源代码即可

 这里就是很简单的爬源代码

import requests
url='https://top.baidu.com/board?tab=realtime'
headers = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0'
    } #伪造ua

def content():
    resposne=requests.get(url=url,headers=headers)
    resposne.encoding='utf-8'
    content=resposne.text
    print(content)
    return content
if __name__ == "__main__":
    content=content()

 

 我们爬完的数据

这里就分为3个模块

re

输入放入里面开始分析

regex101: build, test, and debug regex

<div class="c-single-text-ellipsis">  (.*?) </div>

报错使用
<div class="c-single-text-ellipsis">  (.*?) <\/div>

 这里我们就能发现规律

标题都是在 <div></div>中的

<div class="c-single-text-ellipsis">  (.*?) </div>
报错使用
<div class="c-single-text-ellipsis">  (.*?) <\/div>

 这里我们就匹配了我们的标题

接下来要匹配热搜指数

 同样的道理 进行匹配

 <div class="hot-index_1Bl1a"> (.*?) <\/div>

 这里我就得出了匹配代码 我们可以继续开始写了

import requests
import re
url='https://top.baidu.com/board?tab=realtime'
headers = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0'
    } #伪造ua

def content():
    resposne=requests.get(url=url,headers=headers)
    resposne.encoding='utf-8'
    content=resposne.text
    # print(content)
    return content
def re_text(content):
    fire=re.findall("""<div class="hot-index_1Bl1a"> (.*?) </div>""",content)
    title=re.findall("""<div class="c-single-text-ellipsis">  (.*?) </div>""",content)
    print(fire,title)
    print(len(fire),len(title))
if __name__ == "__main__":
    content=content()
    re_text(content)

 这里就得出来数据

lxml/etree

这里我们使用工具xpath helper

shift+ctrl+x打开工具

按住shift

 能提取出路径

然后我们开始删除前面的路径看看能不能进行贪婪提取

 发现我们提取出来了所有标题

//div[@class='c-single-text-ellipsis']

那我们要提取热搜指数

也是一样的

//div[@class='hot-index_1Bl1a']

我们开始写代码

import requests
import re
from lxml import etree
url='https://top.baidu.com/board?tab=realtime'
headers = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0'
    } #伪造ua

def content():
    resposne=requests.get(url=url,headers=headers)
    resposne.encoding='utf-8'
    content=resposne.text
    # print(content)
    return content
def etree_text(content):   #lxml etree
    new_content=etree.HTML(content)
    fire=new_content.xpath("""//div[@class='hot-index_1Bl1a']/text()""")
    title=new_content.xpath("""//div[@class='c-single-text-ellipsis']/text()""")
    print(fire,title)
if __name__ == "__main__":
    content=content()
    etree_text(content)

beautifulsoup

这个工具我自己感觉很好用

我们直接打开网站

对我们想要的数据进行检查

 然后选择右键 复制 css路径

 复制即可 然后我们开始调用 beautifulsoup的select函数开始查找即可  然后需要调用 .get_text()方法取得内容

标题和指数都是这样

import requests
from bs4 import BeautifulSoup
url='https://top.baidu.com/board?tab=realtime'
headers = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0'
    } #伪造ua

def content():
    resposne=requests.get(url=url,headers=headers)
    resposne.encoding='utf-8'
    content=resposne.text
    # print(content)
    return content
def beau_text(content):
    soup=BeautifulSoup(content,'html.parser')    #使用py自带的html.parser解析器
    # print(soup.prettify())    #内容格式化输出
    # print(soup.body)
    title= soup.select('html body div div#sanRoot.wrapper.c-font-normal.rel main.rel.container_2VTvm div.container.right-container_2EFJr div.container-bg_lQ801 div div.category-wrap_iQLoo.horizontal_1eKyQ div.content_1YWBm a.title_dIF3B div.c-single-text-ellipsis')
    title2=[]
    for i in title:
        title=i.get_text()
        # print(title)
        title2.append(title)    #这里我们就取得了热搜名字
    fire=soup.select('html body div div#sanRoot.wrapper.c-font-normal.rel main.rel.container_2VTvm div.container.right-container_2EFJr div.container-bg_lQ801 div div.category-wrap_iQLoo.horizontal_1eKyQ div.trend_2RttY.hide-icon div.hot-index_1Bl1a')
    fire2=[]
    for i in fire:
        fire=i.get_text()
        fire2.append(fire)   #获取热搜指数

if __name__ == "__main__":
    content=content()
    beau_text(content)

这里三大项就结束了

我们开始保存本地和数据库

保存到本地

import requests
import re
from lxml import etree
from bs4 import BeautifulSoup
url='https://top.baidu.com/board?tab=realtime'
headers = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0'
    } #伪造ua

def content():
    resposne=requests.get(url=url,headers=headers)
    resposne.encoding='utf-8'
    content=resposne.text
    # print(content)
    return content
def to_txt(fire,title):
    content=[]
    for i in range(0,len(title)):
        content.append(str(i)+fire[i]+title[i])
    with open('百度新闻.txt','w',encoding='utf-8')as fp:
        for i in content:
            fp.write(i+'\n')

if __name__ == "__main__":
    content=content()
    fire,title=beau_text(content)
    to_txt(fire,title)

传入数据库

我们先要在数据库中设立好

这里我的数据库是spider  表名为百度新闻 

里面的字段

db=pymysql.connect(host="localhost",port=3306,user="root",passwd="111111",db="spider",charset="utf8")

连接数据库


cursor=db.cursor()
设置游标

全部代码

import requests
from bs4 import BeautifulSoup
import pymysql
url='https://top.baidu.com/board?tab=realtime'
headers = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0'
    } #伪造ua
db=pymysql.connect(host="localhost",port=3306,user="root",passwd="214253551",db="spider",charset="utf8")
cursor=db.cursor()  #连接数据库
def content():
    resposne=requests.get(url=url,headers=headers)
    resposne.encoding='utf-8'
    content=resposne.text
    # print(content)
    return content
def beau_text(content):
    soup=BeautifulSoup(content,'html.parser')    #使用py自带的html.parser解析器
    # print(soup.prettify())    #内容格式化输出
    # print(soup.body)
    title= soup.select('html body div div#sanRoot.wrapper.c-font-normal.rel main.rel.container_2VTvm div.container.right-container_2EFJr div.container-bg_lQ801 div div.category-wrap_iQLoo.horizontal_1eKyQ div.content_1YWBm a.title_dIF3B div.c-single-text-ellipsis')
    title2=[]
    for i in title:
        title=i.get_text()
        # print(title)
        title2.append(title)    #这里我们就取得了热搜名字
    fire=soup.select('html body div div#sanRoot.wrapper.c-font-normal.rel main.rel.container_2VTvm div.container.right-container_2EFJr div.container-bg_lQ801 div div.category-wrap_iQLoo.horizontal_1eKyQ div.trend_2RttY.hide-icon div.hot-index_1Bl1a')
    fire2=[]
    for i in fire:
        fire=i.get_text()
        fire2.append(fire)   #获取热搜指数
    return fire2,title2
def to_data(fire,title):
    data2=title
    data3=fire
    # sqli='delete from 百度新闻'
    # cursor.execute(sqli)
    # db.commit()
    data1=[]
    for i in range(0,len(title)):
        data1.append(i+1)
        sql="INSERT INTO 百度新闻 (id,title,fire) VALUES ( '" + str(data1[i]) + "', '" + data2[i] + "', '" + data3[i] + "');"
        # print(sql)
        try:
            db.ping(reconnect=True)
            cursor.execute(sql)
            db.commit()
            # print('ok')
        except Exception as err:
            #     # 检查异常原因是否是感兴趣的
            result1 = re.search('Duplicate entry.*key.*PRIMARY', str(err))
            #     # 如果是,什么都不用做
            #     # 否则(也不知道是什么原因),那就回滚吧
            if (result1 == None):
                #         # 如果发生错误则回滚
                db.rollback()
                # 关闭数据库连接
        db.close()
if __name__ == "__main__":
    content=content()
    fire,title=beau_text(content)    #beautifulsoup
    to_data(fire,title)

这里就是全部的代码了 数据库的代码

后面还有一个 是全部全类型的代码 这个只是简单的爬虫

import requests
import re
from lxml import etree
from bs4 import BeautifulSoup
import pymysql
url='https://top.baidu.com/board?tab=realtime'
headers = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0'
    } #伪造ua
db=pymysql.connect(host="localhost",port=3306,user="root",passwd="214253551",db="spider",charset="utf8")
cursor=db.cursor()
def content():
    resposne=requests.get(url=url,headers=headers)
    resposne.encoding='utf-8'
    content=resposne.text
    # print(content)
    return content
# def re_text(content):   #re正则
#     fire=re.findall("""<div class="hot-index_1Bl1a"> (.*?) </div>""",content)
#     title=re.findall("""<div class="c-single-text-ellipsis">  (.*?) </div>""",content)
#     print(fire,title)
#     print(len(fire),len(title))
# def etree_text(content):   #lxml etree
#     new_content=etree.HTML(content)
#     fire=new_content.xpath("""//div[@class='hot-index_1Bl1a']/text()""")
#     title=new_content.xpath("""//div[@class='c-single-text-ellipsis']/text()""")
#     print(fire,title)





def beau_text(content):
    soup=BeautifulSoup(content,'html.parser')    #使用py自带的html.parser解析器
    # print(soup.prettify())    #内容格式化输出
    # print(soup.body)
    title= soup.select('html body div div#sanRoot.wrapper.c-font-normal.rel main.rel.container_2VTvm div.container.right-container_2EFJr div.container-bg_lQ801 div div.category-wrap_iQLoo.horizontal_1eKyQ div.content_1YWBm a.title_dIF3B div.c-single-text-ellipsis')
    title2=[]
    for i in title:
        title=i.get_text()
        # print(title)
        title2.append(title)    #这里我们就取得了热搜名字
    fire=soup.select('html body div div#sanRoot.wrapper.c-font-normal.rel main.rel.container_2VTvm div.container.right-container_2EFJr div.container-bg_lQ801 div div.category-wrap_iQLoo.horizontal_1eKyQ div.trend_2RttY.hide-icon div.hot-index_1Bl1a')
    fire2=[]
    for i in fire:
        fire=i.get_text()
        fire2.append(fire)   #获取热搜指数
    return fire2,title2

# def to_txt(fire,title):    #保存到本地
#     content=[]
#     for i in range(0,len(title)):
#         content.append(str(i)+fire[i]+title[i])
#     with open('百度新闻.txt','w',encoding='utf-8')as fp:
#         for i in content:
#             fp.write(i+'\n')
def to_data(fire,title):
    data2=title
    data3=fire
    # sqli='delete from 百度新闻'
    # cursor.execute(sqli)
    # db.commit()
    data1=[]
    for i in range(0,len(title)):
        data1.append(i+1)
        sql="INSERT INTO 百度新闻 (id,title,fire) VALUES ( '" + str(data1[i]) + "', '" + data2[i] + "', '" + data3[i] + "');"
        # print(sql)
        try:
            db.ping(reconnect=True)
            cursor.execute(sql)
            db.commit()
            # print('ok')
        except Exception as err:
            #     # 检查异常原因是否是感兴趣的
            result1 = re.search('Duplicate entry.*key.*PRIMARY', str(err))
            #     # 如果是,什么都不用做
            #     # 否则(也不知道是什么原因),那就回滚吧
            if (result1 == None):
                #         # 如果发生错误则回滚
                db.rollback()
                # 关闭数据库连接
        db.close()
if __name__ == "__main__":
    content=content()
    # re_text(content)     #正则
    # etree_text(content)   #lxml etree
    fire,title=beau_text(content)    #beautifulsoup
    # to_txt(fire,title)          #保存到本地
    to_data(fire,title)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

爬虫的操作 的相关文章

随机推荐

  • Visual Studio 2019 从依赖包开始手动编译opencv

    windows opencv compile document 本文主要是教你如何从源码编译软件包 建议你通过vcpkg安装完整版本的OpenCV4 含gpu功能 来安装使用 1 依赖项目编译安装 在开始之前必须先安装vcpkg 1 1 准
  • [C/C++]基础 %md,%0md是什么意思

    1 d就是普通的整型输出 2 2d是将数字按宽度为2 采用右对齐方式输出 若数据位数不到2位 则左边补空格 3 02d和 2d差不多 只不过是左边补0 修饰符 格式说明 意义 1 m md 以宽度为m输出整型数 输出不足m位时 左补空格 2
  • 首发

    译者 Linstancy 责编 Jane 出品 AI科技大本营 公众号id rgznai100 回顾 CVPR 2018 旷视科技有 8 篇论文被收录 如高效的移动端卷积神经网络 ShuffleNet 语义分割的判别特征网络 DFN 优化解
  • 我的世界java版如何看坐标_我的世界中怎么查看坐标,坐标系统详解

    本篇教程将通过图文的形式一步步教你在我的世界中查看理解坐标系统 XYZ 坐标系统解释 我的世界地图有XYZ3个坐标 通过XYZ来显示你所处地图的区域 下面是每个坐标的详解 X 显示你在地图上的 东 西 位置 正数表示东 负数表示西 Y 显示
  • 什么是域名? 什么是DNS?

    域名 关于域名 百度百科是这样介绍的 百度百科 https baike baidu com item E5 9F 9F E5 90 8D 86062 域名 英语 Domain Name 又称网域 是由一串用点分隔的名字组成的Internet
  • 深入理解数据结构—简单链表

    一 简单链表结构 include
  • python异步requests_Python asyncio requests 异步爬虫

    python asyncio requests async await crawler 一 情景 抓取大量URL 每个URL内信息量较少 任务清单 发送URL请求N次 接受并处理URL响应N次 二 分析 如果每个页面依次抓取的话 任务流程
  • Unity脚本设置Animator单个状态的speed

    Unity脚本设置Animator单个状态的speed 直接上代码 private Animator anim private AnimatorController animController private void Awake ani
  • KMP算法详解

    什么是KMP算法 有句话可以这么形容KMP 一个人能走的多远不在于他在顺境时能走的多快 而在于 他在逆境时多久能找到曾经的自己 KMP算法是一个字符串匹配算法 取得是三个发明人的名字首字母 KMP算法的作用 是在一个已知字符串中查找子串的位
  • ide sonar代码审查问题总结

    格式 问题名字 问题出现的次数 Resources should be closed2 资源未关闭 打开发现有两处用到的IO流没有关闭 Conditions should not unconditionally evaluate to TR
  • php mail函数详解,php中mail()函数用法和SMTP工作原理详解

    一个发送E MAIL的脚本也许是你能够在Web 站点上找到的最普通的脚本之一了 虽然它很简单 一个邮件脚本有时会令程序员非常沮丧 PHP中有一个叫做mail 的函数 它只需要知道接收方的地址 和信件主体就可以发送邮件 但是要让mail 按你
  • 【SQLServer】查询SQLServer执行过的SQL记录

    直接贴代码 SELECT TOP 1000 创建时间 QS creation time 查询语句 SUBSTRING ST text QS statement start offset 2 1 CASE QS statement end o
  • Error in mounted hook: “TypeError: Cannot read properties of undefined (reading ‘split‘)“

    我在用vue写页面的时候 其中附件功能是写成组件模式的 然后在调用后 把数据渲染上去的时候 就会报错 具体错误如下图所示 到后面虽然数据确实是渲染出来了 但是控制台会报Error in mounted hook TypeError Cann
  • 100天精通Python(爬虫篇)——第43天:爬虫入门知识大总结

    文章目录 一 爬虫概述 1 为什么要学习爬虫 2 爬虫与Python 3 爬虫合法吗 4 爬虫的矛与盾 5 爬虫原理图 and 流程图 二 相关技术介绍 1 HTML 与 CSS 2 URL网址解释 3 HTTP 与 HTT S 1 常见请
  • Knights of the Round Table【点双连通分量与二分图】

    题目链接 POJ 2942 题意 亚瑟王要给骑士们开会啦 有N个骑士 其中有M对骑士相互之间会吵架 亚瑟王不允许相互吵架的骑士坐在一起 但是他们可以一同坐在餐桌上 只要隔开就可以了 还有就是 出席会议的骑士数必须是奇数 这是为了让投票表决议
  • 海伯利安:开放地图生态的未来与机遇

    本文选自海伯利安CTO邹光先大会演讲 全文如下 前两天有朋友问了我一个问题 他说谷歌地图在全世界覆盖那么广 用户量也非常大 用户体验也很好 在地图这个赛道上 海伯利安的创新和机会在哪里 这是个好问题 值得反复思考 深入思考 结合我们对地图行
  • Maven的配置、安装及测试可用

    1 配置环境变量的话 配置用户变量和系统变量也没差 反正电脑都是一个人使用 先配置M2 HOME 配置MAVEN HOME也可以 我放置Maven的路径是D Program Files x86 apache maven 3 2 2 具体要看
  • 程序的几种结构

    目录 顺序结构 选择结构 循环结构 break和continue的区别 顺序结构 选择结构 表达式 单选结构 if boolean表达式 执行语句 表达式为true执行相应的语句 否则不执行 双选结构 if boolean表达式 执行语句1
  • 小程序语音识别用户体验优化

    文章由来 这里通过简单的对话形式来描述接下来要讲的bug 相关界面在文章中都有展示 可以结合相关图片更好的理解问题 测试小伙伴 界面一直停留在 语音识别中 我 都到识别这一步了 应该是测试环境下后台不稳定吧 你再多试几次 测试小伙伴 我去问
  • 爬虫的操作

    目录 爬虫基本 re etree beautifulsoup 保存本地 连接数据库 基本 re lxml etree beautifulsoup 保存到本地 传入数据库 大致分为 爬虫基本 re etree beautifulsoup 保存