python+selenium获取网页代码

本文介绍如何使用Selenium安装及配置,并通过Firefox浏览器驱动爬取特定网站上的银行数据,包括选择地区和城市,自动翻页并保存网页源代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

step1.安装selnium:pip3 install selnium

step2:下载firefox或chrome浏览器

step3:下载驱动firefox(https://github.com/mozilla/geckodriver/releases)或chrome驱动(https://sites.google.com/a/chromium.org/chromedriver/ 或者 http://npm.taobao.org/mirrors/chromedriver/),并将驱动放入python安装目录下(就是和python.exe在同一目录)


以股驿台网站(http://www.guyitai.net/stock/bankdata/)获取浙江-杭州地区的银行数据为例:

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
import codecs
# driver = webdriver.Chrome() #选择chrom或firefox浏览器
driver = webdriver.Firefox(executable_path = r'C:\Users\zk\AppData\Local\Programs\Python\Python36\geckodriver')
driver.get("http://www.guyitai.net/stock/bankdata/")

e1 = driver.find_element_by_xpath("//a[@value='0002']") #选择地区:浙江
e1.click()
e2 = driver.find_element_by_xpath("//a[@value='0002-0001']") #选择城市:杭州
WebDriverWait(driver, 10).until(expected_conditions.visibility_of(e2)) #等待页面
e2.click()
count=0
while True:
    count +=1
    locals()['page_'+str(count)]=driver.page_source
    filename=str()
    with codecs.open('page_'+str(count)+'.txt','w',encoding='utf-8') as f:  #保存网页源代码
        f.write( locals()['page_'+str(count)])
    try:
       clickbutton= driver.find_element_by_link_text('下一页')
       clickbutton.click()
    except:
        break
driver.close()  #关闭浏览器

#利用下载的源代码可利用BeautifulSoup进行html数据抓取


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值