这个模块:既能发请求,又能解析,还能执行js
selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行
JavaScript代码的问题
selenium 可以操作浏览器,模拟人的 行为
下载浏览器驱动(chrome):
https://registry.npmmirror.com/binary.html?path=chromedriver/
https://googlechromelabs.github.io/chrome-for-testing/
https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/119.0.6045.105/win64/chromedriver-win64.zip
https://github.com/mozilla/geckodriver/releases/
将驱动放到python解释器目录下,或者配置环境变量
下载模块:pip install selenium
写python代码,操作浏览器
import time
from selenium import webdriver
# 跟人操作浏览器一样,打开了谷歌浏览器,拿到浏览器对象
bro=webdriver.Firefox()
# 在地址栏中输入地址
bro.get('https://www.baidu.com')
time.sleep(5)
bro.close()
bro为实例化所得对象
bro.get('网址地址')
bro.close()
bro.implicitly_wait(10)
,从页面中找标签,如果找不到,就等待bro.maximize_window()
bro.page_source)
from selenium.webdriver.common.by import By
bro.find_element(by=By.选择器,value='')
bro.find_elements(by=By.选择器,value='')
找到的标签.click()
找到的标签.send_keys()
from selenium import webdriver
from selenium.webdriver.common.by import By
bro = webdriver.Firefox()
bro.get('https://www.baidu.com')
bro.implicitly_wait(10)
bro.maximize_window()
# 找到登录按钮
a_login = bro.find_element(by=By.LINK_TEXT, value='登录')
a_login.click()
# 往输入框中写文字
username = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__userName')
username.send_keys('13437238745')
password = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__password')
password.send_keys('caimina1')
agree = bro.find_element(By.ID, 'TANGRAM__PSP_11__isAgree')
agree.click()
submit = bro.find_element(By.ID, 'TANGRAM__PSP_11__submit')
submit.click()
bro.close()
如果我们做爬虫,我们只是为了获取数据,不需要非有浏览器在显示 ⇢ \dashrightarrow ⇢ 隐藏浏览器图形化界面
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('blink-settings=imagesEnabled=false') #不加载图片, 提升速度
chrome_options.add_argument('--headless') #浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
bro = webdriver.Chrome(options=chrome_options)
bro.get('https://www.cnblogs.com/liuqingzheng/p/16005896.html')
print(bro.page_source)
time.sleep(3)
bro.close()
bro.get_attribute('src')
bro.text
tag.size
bro.location
tag.id
tag.tag_name
divs=bro.find_elements(By.TAG_NAME,'div')
div=bro.find_element(By.CLASS_NAME,'postDesc').text
div=bro.find_element(By.CSS_SELECTOR,'div.postDesc').text
#id为topics下的div下的div中类为postDesc
div=bro.find_element(By.CSS_SELECTOR,'#topics > div > div.postDesc').text