简单爬取百度页面以及爬出输入搜索内容案例

from selenium import webdriver
import time

# 设置 Chrome 驱动程序路径
driver_path = '/path/to/chromedriver'

# 目标搜索关键词
search_query = '需要搜索的内容'

# 设置 Chrome 浏览器选项
options = webdriver.ChromeOptions()
options.add_argument('--headless')  # 无头模式运行浏览器,即不打开实际浏览器窗口
options.add_argument('--disable-gpu') #这个是禁用gpu
options.add_argument('--no-sandbox') # 这个是禁用沙箱

# 启动 Chrome 浏览器
driver = webdriver.Chrome(executable_path=driver_path, options=options)

try:
    # 打开百度搜索页面
    driver.get('https://www.baidu.com')
    
    # 查找搜索框并输入关键词
    search_box = driver.find_element_by_css_selector('input#kw') #这个代表的是搜索框的class
    search_box.send_keys(search_query) 
    
    # 提交搜索表单
    search_box.submit()
    
    # 等待搜索结果页面加载完全
    time.sleep(3)
    
    # 获取搜索结果(假设获取前5个搜索结果)
    search_results = driver.find_elements_by_css_selector('.result .t a') #替换标题链接class
    
    for index, result in enumerate(search_results[:5], start=1):
        # 输出搜索结果的标题和链接
        title = result.text
        link = result.get_attribute('href')
        print(f"搜索结果 {index}: {title} - {link}")

except Exception as e:
    print(f"爬取过程出现异常: {str(e)}")

finally:
    # 关闭浏览器驱动
    driver.quit()

如果浏览器不同,自行更换即可,另 此文章使用的是CSS,如果喜欢使用xpath的小伙伴自行更改即可,虽说xpath好用,但是简单的爬取,css比较简单直接;

文章中需要替换的内容,根据F12中,字段class自行替换即可

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.房东的猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值