本程序基于Python和Selenium可以实现登录微博,输入关键词搜索,获取搜索结果页面中的微博内容和发布时间的功能。对于更复杂的微博数据爬取,需要根据具体需求进行修改。同时,需要注意遵守相关法律法规和网站规定,不得进行恶意攻击和侵犯他人隐私等行为。
from selenium import webdriver
import time
# 设置Chrome浏览器的驱动程序路径
chrome_driver_path = "/path/to/chrome/driver"
# 初始化Chrome浏览器驱动
driver = webdriver.Chrome(chrome_driver_path)
# 打开微博登录页面
driver.get("https://weibo.com/login.php")
# 等待页面加载完成
time.sleep(5)
# 输入微博账号和密码
username = driver.find_element_by_name("username")
password = driver.find_element_by_name("password")
username.send_keys("your_username")
password.send_keys("your_password")
# 点击登录按钮
login_button = driver.find_element_by_xpath("//div[@class='info_list login_btn']/a")
login_button.click()
# 等待登录成功后页面加载完成
time.sleep(10)
# 在搜索框中输入要查找的关键词
search_box = driver.find_element_by_xpath("//input[@node-type='searchInput']")
search_box.send_keys("your_keyword")
# 点击搜索按钮
search_button = driver.find_element_by_xpath("//a[@action-type='searchSubmit']")
search_button.click()
# 等待搜索结果页面加载完成
time.sleep(10)
# 获取搜索结果页面中的微博内容
weibo_elements = driver.find_elements_by_xpath("//div[@action-type='feed_list_item']")
for weibo_element in weibo_elements:
# 获取微博内容和发布时间
content_element = weibo_element.find_element_by_xpath(".//p[@node-type='feed_list_content']")
content = content_element.text.strip()
time_element = weibo_element.find_element_by_xpath(".//a[@node-type='feed_list_item_date']")
publish_time = time_element.get_attribute("title")
print(content, publish_time)
# 关闭浏览器窗口
driver.close()