Selenium库爬取今日头条网页数据
时间: 2023-07-27 16:07:40 浏览: 72
使用Selenium库可以模拟真实浏览器行为,更加灵活地爬取网页数据。下面是使用Selenium库爬取今日头条网页数据的示例代码:
```python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 创建Chrome浏览器对象
chrome_options = Options()
chrome_options.add_argument('--headless') # 无头模式
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(options=chrome_options)
# 访问网页
url = 'https://www.toutiao.com/ch/news_hot/'
driver.get(url)
# 等待元素加载完成
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'title-box')))
# 获取新闻标题
titles = driver.find_elements_by_class_name('title-box')
for title in titles:
print(title.find_element_by_tag_name('a').text)
# 关闭浏览器
driver.quit()
```
在这个示例中,我们首先创建了Chrome浏览器对象,并设置了无头模式和禁用GPU,这样可以加快页面加载速度。然后访问目标网页,并等待页面中的新闻标题加载完成,最后使用`find_elements_by_class_name`方法获取所有class为`title-box`的元素,并遍历每个元素,提取其中的`a`标签的文本内容,即为新闻标题。
需要注意的是,使用Selenium库需要下载浏览器驱动,这里使用的是Chrome浏览器,需要下载对应版本的Chrome驱动,并将其路径添加到系统环境变量中。