栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

爬虫selenium+BeautifulSoup组合

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

爬虫selenium+BeautifulSoup组合

selenium+BeautifulSoup组合(自动翻页爬取)

使用selenium获取网页,然后交给BeautifulSoup解析和提取。

一、selenium

1.selenium安装

pip install selenium # Windows电脑安装selenium

2.设置浏览器引擎
根据自己的浏览器版本下载Chrome的安装包
下载地址https://registry.npmmirror.com/binary.html?path=chromedriver/

from selenium import  webdriver
driver = webdriver.Chrome() 
二、 BeautifulSoup
from bs4 import BeautifulSoup
三、项目构建 1.打开网页,并手动登录账号
driver.get('https://**********') 
time.sleep(20)##在此期间等待页面加载并输入账号密码
2. 翻页爬取


如上图,网页有一个输入页面的文本框,可以用循环代码实现自动填入页码值并翻页的功能:

for i in range(1,1000):##表示查询1~999页
    button=driver.find_element_by_name('nowpage')
    button.clear()
    button.send_keys(i)
    button=driver.find_element_by_class_name('bt')
    button.click()
    time.sleep(2)
    pageSource = driver.page_source # 获取完整渲染的网页源代码
    soup = BeautifulSoup(pageSource,'html.parser')
    comments1 = soup.find_all(class_='linem')
    for comment1 in comments1:
       print(comment1.text)
3.关闭浏览器

driver.close()

四、selenium提取数据的方法

find_element_by_tag_name:通过元素的名称选择
find_element_by_class_name:通过元素的class属性选择
find_element_by_id:通过元素的id选择
find_element_by_name:通过元素的name属性选择
find_element_by_link_text:通过链接文本获取超链接
find_element_by_partial_link_text:通过链接的部分文本获取超链接

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/917999.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号