挑戰答題題庫爬取

2021-10-14 01:23:08 字數 3666 閱讀 3298

可參考思路

# 抓取平台1

defgetquestionbank

(self)

: url =

''headers =

html = requests.get(url, headers=headers)

.content.decode(

'gbk'

) tree = etree.html(html)

content = tree.xpath(

'//div[@class="clearfix neirong"]/p/text()'

)# print(content)

return content

# 資料清洗

defparsequestions

(self, content)

:# 最終的結果集

arrays =

# 臨時工具陣列

temp =

# 存選項

options =

# 跳過,「選擇詞語的正確詞形」這個題型以後再說

skip =

0for i in content:

i = i.replace(

'\u3000',''

)# 答案

if i.startswith(

'參***'):

if skip ==1:

skip =

0continue

# print(i+" "+str(temp))

# 選項對應的陣列下標

iflen

(re.findall(r'[a-ea-e]'

, i))==

0:continue

index =

ord(re.findall(r'[a-ea-e]'

, i)[0

].upper())

-65# 選項對應的答案內容

answer = options.pop(index)

# print(str(len(temp))+' '+str(temp)+' '+answer)

, answer)[0

])# 存入結果集))

# print(temp)

# 陣列清空,為下次做準備

temp.clear(

)# 陣列清空,為下次做準備

options.clear(

)# 選項

elif re.match(r'^[a-e]+'

, i)

:if skip ==1:

continue

# 題幹

else

:# 這個題型以後再說

if'選擇詞語的正確詞形'

in i:

skip =

1continue

# 去除特殊字元,並加入

(temp.pop()if

len(temp)!=0

else'')

+re.sub(

'\w+',''

, i)

.replace(

"_",'')

)# print(arrays)

# print(len(arrays))

return arrays

# 資料持久化

defstorequestions

(self, arrays)

: db = pymysql.connect(host=

"localhost"

, port=

3306

, user=

"root"

, passwd=

"1061700625"

, db=

"learn"

) cursor = db.cursor(pymysql.cursors.dictcursor)

# 使用cursor()方法獲取操作游標,按字典返回

for item in arrays:

print

('*'*20

)print

(item)

iflen

(item)

<2:

print

(">> 資料錯誤"

)continue

question = item[0]

options =

none

answer = item[1]

sql =

"select * from bank where question='{}'"

.format

(question)

cursor.execute(sql)

data = cursor.fetchall()if

len(data)!=0

:print

(">> 資料存在"

)continue

sql =

"insert into bank(question,options,answer) values('{}','{}','{}')"

.format

(question, options, answer)

try:

cursor.execute(sql)

# 使用execute方法執行sql語句

db.commit(

)# 提交到資料庫執行

print

(">> 插入完成"

)except exception as e:

print

(">> 插入失敗"

)print

('*'*20

+'\r\n'

+str

(e)+

'\r\n'

+'*'*20

) db.rollback(

)# 發生錯誤時回滾

cursor.close(

) db.close(

)if __name__ ==

'__main__'

: bank = bank(

) content = bank.getquestionbank(

) arrays = bank.parsequestions(content)

bank.storequestions(arrays)

Python題庫 簡答題

1.命名空間和作用域的關係 命名空間定義了在某個作用域內變數名和繫結值之間的對應關係,命名空間是鍵值對的集合,變數名與值是一一對應關係。作用域定義了命名空間中的變數能夠在多大範圍內起作用。2.裝飾器函式的作用?寫乙個裝飾器程式 在不修改原函式及其呼叫方式的情況下對原函式功能進行擴充套件。def ou...

c 簡答題題庫 C 簡答題集錦

c 簡答題集錦 問題1 什麼是演算法?演算法應包括哪兩部分?答 所謂演算法,是指為解決乙個問題而採取的方法和步驟,或者說是解題步驟的精確描述。演算法應包括設計演算法和執行演算法兩部分。問題2 結構化程式設計的特徵是什麼?答 結構化程式設計方法從程式設計思想上要求自頂向下,逐步求精 從程式的具體結構上...

聊聊答題應用題庫的建立

另一方面,對於題目答案的搜尋。常見的幾種做法是直接用題目作為搜尋關鍵字開啟瀏覽器,或者是問題加選項搜尋,獲取搜尋引擎搜尋的結果數量。通過結果數量來判斷問題和選項的相關性從而判斷問題的答案,一般來說這種方式獲取的答案都是不太準確的,一是因為現在題目的出題方式越來越詭異,二是相關性越大並不一定就意味著是...