使用selemium在百度中自动搜索数据嗨客并爬取搜索到的标题名称
以下是使用Python和Selenium在百度中自动搜索“数据嗨客”,并爬取搜索到的标题名称的示例代码:
from selenium import webdriver
# 创建浏览器对象
driver = webdriver.Chrome()
# 打开百度首页
driver.get('https://www.baidu.com/')
# 找到搜索框并输入关键词
search_box = driver.find_element_by_id('kw')
search_box.send_keys('数据嗨客')
# 找到搜索按钮并点击
search_btn = driver.find_element_by_id('su')
search_btn.click()
# 等待搜索结果页面加载完成
driver.implicitly_wait(10)
# 找到搜索结果列表
results = driver.find_elements_by_xpath('//div[@class="result c-container "]')
# 遍历搜索结果并输出标题名称
for result in results:
title = result.find_element_by_xpath('.//h3').text
print(title)
# 关闭浏览器
driver.quit()
运行上述代码后,将会自动打开Chrome浏览器并在百度中搜索“数据嗨客”,然后输出搜索结果页面中所有标题名称。注意,在使用Selenium时,需要先安装对应的浏览器驱动。上述代码中使用的是Chrome浏览器,所以需要下载Chrome驱动并将其添加到系统环境变量中
原文地址: https://www.cveoy.top/t/topic/gfDn 著作权归作者所有。请勿转载和采集!