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

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自行替换即可

猜你喜欢

转载自blog.csdn.net/m0_74940474/article/details/140384785