【酱浦菌-爬虫项目】四种方法爬取百度首页信息

项目原理:

  1. 首先,定义了四个函数,每个函数都有不同的功能:

    • func1():发送一个GET请求到百度网站,并获取响应内容,演示如何使用`requests`库来获取网页内容。

    • func2():发送一个GET请求到百度网站,并获取响应内容。然后将响应内容保存为名为“baidu.png”的图片文件。

    • func3():使用Splash执行Lua脚本,加载百度网站并等待2秒,然后返回HTML内容。演示如何使用Splash来渲染JavaScript并获取渲染后的网页内容。

    • func4():使用Splash执行Lua脚本,加载百度网站,输入搜索关键词“SXT”,点击搜索按钮,等待2秒,然后返回HTML内容。演示如何使用Splash来模拟用户在网页上的交互操作。

  2. 每个函数的具体步骤如下:

    • 构建请求URL,包含了百度网站的地址。

    • 设置HTTP请求的头部信息,模拟了一个Chrome浏览器的请求。

    • 发送GET请求到指定的URL,获取响应内容。

    • 对于func2func4,将响应内容保存为图片文件。

    • 打印响应内容或其他信息。

  3. 最后,通过调用这四个函数,可以实现不同的操作,例如获取网页内容、下载图片等。

完整代码: 

import requests

#三个接口
def func1():
    url = 'https://www.baidu.com/'
    base_url = f'http://localhost:8050/render.html?url={url}&wait=1'
    resp = requests.get(base_url)
    print(resp.text)
    
def func2():
    url = 'https://www.baidu.com/'
    base_url = f'http://localhost:8050/render.html?url={url}&wait=1'
    resp = requests.get(base_url)
    with open("img\\" + "baidu" +'.png', 'wb') as f:
        f.write(resp.content)
    print(resp.text)
    
def func3():
    url = 'https://www.baidu.com/'
    lua = f'''
    function main(splash, args)
        splash:go(""{url})
        splash:wait(2)
        return splash:html()
    '''
    base_url = f'http://localhost:8050/execute?lua_source={lua}'
    resp = requests.get(base_url)
    with open("img\\" + "baidu" +'.png', 'wb') as f:
        f.write(resp.content)
    print(resp.text)

def func4():
    url = 'https://www.baidu.com/'
    lua = f'''
    function main(splash, args)
        splash:go("{url}")
        input = splash:select("#kw")
        input:send_text("SXT")
        button = splash:select('#su)
        button:mouse_click()
        splash:wait(2)
        return splash:html()
    '''
    base_url = f'http://localhost:8050/execute?lua_source={lua}'
    resp = requests.get(base_url)
    with open("img\\" + "baidu" +'.png', 'wb') as f:
        f.write(resp.content)
    print(resp.text)

if __name__ == '__main__':
    func1()
    func2()
    func3()
    func4()

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值