使用selenium爬取网页

今天学习了使用selenium爬取网页。

#本地Chrome浏览器的可视模式设置:
from selenium import webdriver #从selenium库中调用webdriver模块
driver = webdriver.Chrome() # 设置引擎为Chrome,真实地打开一个Chrome浏览器


#本地Chrome浏览器的静默默模式设置:
from selenium import  webdriver #从selenium库中调用webdriver模块
from selenium.webdriver.chrome.options import Options # 从options模块中调用Options类

chrome_options = Options() # 实例化Option对象
chrome_options.add_argument('--headless') # 把Chrome浏览器设置为静默模式
driver = webdriver.Chrome(options = chrome_options) # 设置引擎为Chrome,在后台默默运行

使用selenium提取数据的方法是

使用selenium爬取网页_第1张图片

在这个过程中,对象的转换过程

使用selenium爬取网页_第2张图片
使用selenium爬取网页_第3张图片

selenium还可以搭配BeautifulSoup解析提取数据,前提是先获取字符串格式的网页源代码

HTML源代码字符串 = driver.page_source

写了一个用selenium来爬取QQ音乐歌词的爬虫:

from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('https://y.qq.com/n/yqq/song/000xdZuV2LcQ19.html')
time.sleep(2)
comments = driver.find_element_by_class_name('js_hot_list').find_elements_by_class_name('js_cmt_li')#这里查找的name是网页中name的最后一个就行
for comment in comments:
    i = comment.find_element_by_tag_name('p')
    print('评论:','\n',i.text,'\n','---------------')
for x in range(5):
    press = driver.find_element_by_class_name('js_get_more_hot')
    press.click()#这里点击“加载更多”按钮,每点击一次多加载15个评论
    time.sleep(2)
    comments1 = driver.find_element_by_class_name('js_hot_list').find_elements_by_class_name('js_cmt_li')#这里查找到的对象是一个列表,因为前15个评论内容已经爬取过,这里爬取15*X个后面的内容
    b = len(comments1)-(x+1)*15
    comments2 = comments1[b:]
    for comment1 in comments2:
        a = comment1.find_element_by_tag_name('p')
        print('评论:','\n',a.text,'\n','---------------')
driver.close()#最后务必要关闭浏览器

使用Xpath

使用selenium爬取网页_第4张图片

复制的内容是://[@id=“teacher”],但是在python中""引号表示的是字符串,所以这里要用进行转义,也就是://[@id=“teacher”]

teacher = driver.find_element_by_xpath('//*[@id=\"teacher\"]')

seleniu的中文文档

https://selenium-python-zh.readthedocs.io/en/latest

你可能感兴趣的:(python学习)