今天学习的是selenuim的无头浏览器,这个说法蛮有意思的。就是说我们在爬取数据的过程中并不希望浏览器不断打开新的网页,但是又可以爬到子网页的内容。所以叫无头浏览器。
上代码:
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.by import By
import time
# 准备好参数配置,这些默认参数传进Chrome里面,就可以变成无头浏览器,浏览器在selenuim的控制下也不会打开,不用背,要用的时候直接过来复制黏贴
opt = Options()
opt.add_argument("--headless")
opt.add_argument("--disbale-gpu")
web = Chrome(options=opt) # 把参数配置设置到浏览器中
web.get("https://www.endata.com.cn/BoxOffice/BO/Year/index.html")
time.sleep(2)
# 定位到下拉列表
sel_el = web.find_element_by_xpath('//*[@id="OptionDate"]')
# 对元素进行包装, 包装成下拉菜单
sel = Select(sel_el)
# 让浏览器进行调整选项
for i in range(len(sel.options)): # i就是每一个下拉框选项的索引位置
sel.select_by_index(i) # 按照索引进行切换
time.sleep(2)
table = web.find_element_by_xpath('//*[@id="TableList"]/table')
print(table.text) # 打印所有文本信息
print("===================================")
print("运行完毕. ")
web.close()
# 如何拿到页面代码Elements(经过数据加载以及js执行之后的结果的html内容)
#print(web.page_source)
总结:今天新的了一个select,在webdriver的support.select导入select,他可以帮我们把一个列表包装成一个下拉菜单。进行for循环的时候可以根据select.select_by_index来 自动切换子页面。另外学习了webdriver.chrome.options,选择合适的参数可以包装成无头浏览器。最后就是可以直接获得经过js执行数据加载的html内容,简而言之就是直接拿到客户端渲染后的html数据。