前言
為幫助懶狗實現不用背題,輕松通過線上考試的目標。
需要把目標網站上的題庫以及對應的答案,全部爬取到本地。
技術選型
通過控制臺發現點擊下一題并不會產生新的資源鏈接。也就是說該頁面是動態頁面,那么像BeautifulSoup之類的庫就沒有用武之地了。
綜上,所以考慮使用Selenium來模擬用戶行為爬取數據。
準備步驟
·不必多說
pip3 install selenium
· 因為需要Chrome Driver和當前使用Chrome版本一致,所以可以在下方網頁中,找到對應版本進行下載
http://chromedriver.storage.googleapis.com/index.html
實戰
配置一下Chrome Driver路徑,指定訪問URL,啟動。
如果Chrome瀏覽器能打開所指定網頁,基本工作就算完成。
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
if __name__ == '__main__':
url = ""
headers = {
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36"
}
chrome_driver = "/usr/local/bin/chromedriver"
wb = webdriver.Chrome(executable_path=chrome_driver)
wb.get(url)
· 獲取該頁面題目,通過Full XPath
subject = wb.find_element_by_xpath(
'/html/body/div/div/div/div/div[2]/div[1]/div[2]/div[1]/div/div[1]/section/div/div[1]/div[2]/span')
·獲取該頁面答案,這里用XPath肯定是行不通的,因為每一頁答案位置不固定
觀察頁面發現被選中答案的類選擇器與未被選中不一致,所以從這里入手:
answers = wb.find_elements_by_css_selector('.optionsItems.active')
·題目有了,答案也有了。復制下一題的Full XPath
一個最小單位的獲取流程就結束了。這里用ActionChains來模擬用戶操作:
button = wb.find_element_by_xpath(
'/html/body/div/div/div/div/div[2]/div[1]/div[2]/div[1]/div[2]/div/div[1]/div/div[2]')
ActionChains(wb).move_to_element(button).click(button).perform()
·循環上一個步驟
發現到了最后一題,類選擇器有不同。設置結束條件:
try:
if wb.find_element_by_css_selector('.nextBtn.info') is not None:
break
except NoSuchElementException:
print()
這里需要注意設置了dealy(1),這是因為每次跳轉到一個新頁面后,頁面元素可能還沒加載出來,這個時候直接去通過selenium獲取元素是拿不到的,并且會拋異常。
for index, exam_url in enumerate(exam_urls):
wb.get(exam_url)
# 開始做題
delay(1)
for i in range(500):
getSubject()
try:
if wb.find_element_by_css_selector('.nextBtn.info') is not None:
break
except NoSuchElementException:
print()
總結
Selenium提供了很多查找頁面元素的方法。
ActionChains也非常強大,提供了許多模擬用戶動作的方法。
如有興趣可自行研究,本案例為幫助他人即興所寫,不再深入。
本文內容不用于商業目的,如涉及知識產權問題,請權利人聯系51Testing小編(021-64471599-8017),我們將立即處理