简单理解爬虫的概念

简单来说:

爬虫,即网络蜘蛛,是伪装成客户端与服务器进行数据交互的程序。

代码

代码教程分享(无偿):

思路

1.获取网页的源码
复制代码
python

def askURL(url):
    head={
        "User-Agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Mobile Safari/537.36 Edg/121.0.0.0"
    }
    request = urllib.request.Request(url,headers=head)
    html= ""
    try:
        response=urllib.request.urlopen(request)
        html=response.read().decode("utf-8")
        #print(html)
    except urllib.error.URLError as e:
        if hasattr(e,"code"):
            print(e.code)
        if hasattr(e,"reason"):
            print(e.reason)
    return html
复制代码

用个循环,根据网页制定一下url

找到用于伪装客户端User-Agent

在network里刷新一下网页,找到发送的标头header

这个是user-agent:Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Mobile Safari/537.36 Edg/121.0.0.0

用urllib获取你制定的url的源码

在 try 块中:

调用 urllib.request.urlopen(request) 发送HTTP请求,并获取响应对象 response。

通过 response.read() 获取服务器返回的原始二进制数据。

使用 decode("utf-8") 方法将二进制数据解码成UTF-8编码的字符串,并将其赋值给变量 html。

如果在执行 urlopen 函数过程中出现 urllib.error.URLError 异常,则进入 except 块:

判断异常对象是否包含 .code 属性,如果有则打印出HTTP状态码。

再判断异常对象是否包含 .reason 属性,如果有则打印出错误原因。

最后,无论是否发生异常,都返回抓取到的网页HTML内容(即变量 html)

2.解析数据
复制代码
python

def getDate(baseurl):
    datalist = []
    # 1.爬取网页
    for i in trange(0,10):
        url = baseurl + str(i*25)
        html = askURL(url)      #保存获取到的网络源码
        soup = BeautifulSoup(html,"html.parser")
        for item in soup.find_all('div',class_="item"):
            # 2.逐一解析数据
            item =str(item)
            data=[]
            name = re.findall(findName,item)[0]
            data.append(name)
            link = re.findall(findLink,item)[0]
            data.append(link)
            img = re.findall(findImagesrc,item)[0]
            data.append(img)
            rating = re.findall(findRating,item)
            data.append(rating)
            comment = re.findall(findComment,item)
            if len(comment)!=0:
                comment=comment[0].replace("。","")
                data.append(comment)
            else:
                data.append("  ")
            datalist.append(data)
 
    return datalist
复制代码

BeautifulSoup

bs4是一个强大的库,用于从HTML和XML文件中提取数据,它能够将复杂的HTML结构转换成树形结构(即元素树),使得开发者可以方便地搜索、遍历以及修改网页内容。

"html.parser": 这是BeautifulSoup用来解析HTML文档的解析器。在这个案例中,它是指Python自带的标准HTML解析器。除了标准的解析器外,BeautifulSoup还可以配合其他第三方解析器如 lxml 来使用。

用bs4和re筛选信息

3.保存数据 写入excel表中

需要用到xwlt库

复制代码
python

def savedata(datalist,savepath):
    book = xlwt.Workbook(encoding="utf-8",style_compression=0)   #压缩样式效果,设为0
    sheet = book.add_sheet('top250',cell_overwrite_ok=True)  #每个单元在写入时覆盖以前的内容
    col = ('电影中文名','电影详情链接','图片链接','电影评分','电影热评')
    for i in range(0,len(col)):
        sheet.write(0,i,col[i])   #列名
    for i in range (0,250):
        data = datalist[i]
        for j in range (0,len(col)):
            sheet.write(i+1,j,data[j])
 
    book.save(savepath)
复制代码
相关推荐
工业HMI实战笔记6 分钟前
玩具制造HMI:注塑成型的快速换模与质量监控界面
人工智能·学习·交互·制造
SEO_juper2 小时前
你的服务器正在被 AI 爬虫“白嫖“带宽:2026 用日志把 Googlebot 和 AI 洪流分开算账(附脚本)
运维·人工智能·爬虫·python·chatgpt·seo
兰亭妙微UI设计公司5 小时前
UI设计外包项目复盘沉淀|兰亭妙微:交互设计复盘,到底要写哪些内容
交互
躺柒10 小时前
读数据可视化29可视化中的交互(下)
信息可视化·人机交互·交互·可视化·数据可视化·交互技术
2601_962295331 天前
如何python实现网页的自动化
python·selenium·beautifulsoup·requests·网页自动化
云雀衔光1 天前
MCP + 应用生成:让 AI 直接产出可交互的应用
java·人工智能·测试工具·microsoft·交互·ai编程
m0_547486661 天前
《Python爬虫大数据采集与挖掘》全套PPT课件2026
爬虫·python·powerpoint
Experience-摆渡2 天前
MediaCrawler舆情分析系统实测:7大平台爬虫的商用授权红线与风控现状
爬虫
2601_962381582 天前
Python爬虫requests框架详解!零基础学会网络请求,抓取全网数据
爬虫·python·网络请求·数据抓取·requests框架
smartpi_ai2 天前
自学习“放着不动“会自动退出吗?超时退出缺席的交互兜底、退出条件挂串口的状态联动设计
学习·microsoft·交互