python系列25:使用selenium进行自动化网页操作

1. 背景

python中requests发送请求后,没有办法执行里面的javascript代码,因此有很多信息会爬取不到。这里有个自动化测试的工具selenium,可以模拟网页打开的过程。使用pip install即可安装。

2. 使用方法

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("--headless") 
options.add_argument("start-maximized")

# 这里要去官网上下载chromedriver
driver = webdriver.Chrome(executable_path =..., options = options)
# 静待5秒钟,让网页加载完毕
driver.implicitly_wait(5)
driver.get("https://www.jst-purple.com.cn/purple/index.php#searchProduct")
for page in range(1,247):
    # 点击下一页按钮
    next_page = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.LINK_TEXT, '下一页')))
    next_page.click()
    element = driver.find_element_by_id('div_content_sub')
    for i in element.text.split('\n'):
    	......

猜你喜欢

转载自blog.csdn.net/kittyzc/article/details/125312229
今日推荐