Python爬蟲實現(xiàn)selenium處理iframe作用域問題
項目場景:
在使用selenium模塊進(jìn)行數(shù)據(jù)爬取時,通常會遇到爬取iframe中的內(nèi)容。會因為定位的作用域問題爬取不到數(shù)據(jù)。
問題描述:
我們以菜鳥教程的運(yùn)行實例為案例。
按照正常的定位

會以文本塊生成xpath為/html/body/text()。這樣的話根據(jù)xpath進(jìn)行如下代碼編寫。
#!/user/bin/
# -*- coding:UTF-8 -*-
# Author:Master
from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path="./chromedriver")
driver.get('https://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python3')
time.sleep(2)
text = driver.find_element_by_xpath('/html/body').text
print(text)
time.sleep(5)
driver.quit()
執(zhí)行結(jié)果:

很明顯這并不是想要的結(jié)果。
原因分析:
當(dāng)我們打開抓包工具定位到Hello, World!文本的時候會發(fā)現(xiàn),該文本是在一個iframe中。這樣的話我們xpath所定位到的內(nèi)容則是大的html中的路徑。我們需要的內(nèi)容則是在iframe中的小的html中。
解決方案:
通過分析發(fā)現(xiàn),想要解決問題的實質(zhì)就是改變作用域。通過switch_to.frame(‘id')方法來改變作用域就可以了。
重新編寫代碼:
#!/user/bin/
# -*- coding:UTF-8 -*-
# Author:Master
from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path="./chromedriver")
driver.get('https://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python3')
time.sleep(2)
driver.switch_to.frame('iframeResult')
text = driver.find_element_by_xpath('/html/body').text
print(text)
time.sleep(5)
driver.quit()
查看運(yùn)行結(jié)果:

到此這篇關(guān)于Python爬蟲實現(xiàn)selenium處理iframe作用域問題的文章就介紹到這了,更多相關(guān)selenium iframe作用域內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Tornado Web Server框架編寫簡易Python服務(wù)器
這篇文章主要為大家詳細(xì)介紹了Tornado Web Server框架編寫簡易Python服務(wù)器,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07
Flask Paginate實現(xiàn)表格分頁的使用示例
flask_paginate是Flask框架的一個分頁擴(kuò)展,用于處理分頁相關(guān)的功能,本文就來介紹一下Flask Paginate實現(xiàn)表格分頁的使用示例,感興趣的可以了解一下2023-11-11

