python實驗報告二

2021-09-25 09:00:09 字數 2795 閱讀 2370

import bs4

import re

import requests

import json

headers =

'''使用requests爬取網頁檔案'''

'''使用bs4爬取檔案內容'''

def parsesearch(text):

soup = bs4.beautifulsoup(text,"html.parser")

tags = soup.find_all('span')

for tag in tags:

cont = tag.string

cont = cont.rstrip('個')

cont = cont.replace(',','')

writefile('搜尋結果為:'+str(cont))

print('搜尋結果為:',cont)

def parsehtml(text,json_data):

soup = bs4.beautifulsoup(text, "html.parser")

tags = soup.find_all('div', class_='result c-container ')

for tag in tags:

cont = str(tag .a)

name = tag.a.text

name = str(name)

rule = re.compile(r'ref="(.*?)"')

if (cont is not none):

data = rule.search(cont)

data = data.group()

data = data.lstrip('ref="',)

data = data.rstrip('"')

data = str(data)

writefile(name+'\n'+data)

json_data[name] = data

'''檔案寫入操作'''

def writefile(data,param = true):

with open('txt.txt', 'a+', encoding="utf-8") as fp:

fp.write(data)

fp.write('\n')

if param == false:

fp.close()

'''json檔案寫入'''

def writejson(json_data):

json_data = json.dumps(json_data, indent=4, ensure_ascii=false)

with open('txt.json', 'a+', encoding="utf-8") as fp:

fp.write(json_data)

'''main函式'''

writefile("第"+str(pn)+"頁的搜尋結果為:")

parsehtml(text,json_data)

pn+=1

if(pn == 100):

print("爬取結束,請看txt.txt")

writefile("爬取結束", false)

break

writejson(json_data)

main()

import json

def compare():

with open('txt1.json', 'r', encoding="utf-8") as fp:

data1 = json.load(fp)

with open('txt2.json', 'r', encoding="utf-8") as fp:

data2 = json.load(fp)

#用於儲存資料的臨時字典

dict = {}

#匹配比較

for i in list(data1.keys()):

if i not in data2:

dict[i] = data1[i]

for i in list(data2.keys()):

if i not in data1:

dict[i] = data2[i]

#寫入操作

json_data = json.dumps(dict, indent=4, ensure_ascii=false)

with open('txt.json', 'a+', encoding="utf-8") as fp:

fp.write(json_data)

fp.close()

print("over")

compare()

Python實驗報告二

安徽工程大學 python程式設計實驗報告 班級物流192姓名周玉芳學號3190505226 日期2020.3.24指導老師修宇 實驗目的 1 掌握資料的輸入輸出的方法 2 熟悉順序結構程式中語句的執行過程 3 掌握順序結構程式的方法。實驗條件 pc機或者遠端程式設計環境 實驗內容 1 完成三個程式...

實驗報告二

中國人民公安大學 chinese people public security university 網路對抗技術 實驗報告 實驗二網路嗅探與欺騙 學生姓名 王嘉豪 年級2014級 區隊5 指導教師 高見資訊科技與網路安全學院 2016年11月7日 還沒完 慢慢完成 實驗任務總綱 2016 2017...

實驗報告二

中國人民公安大學 chinese people public security university 網路對抗技術 實驗報告 實驗二網路嗅探與欺騙 學生姓名 湯堯 學號 201821340024 年級 2018 區隊 網安六區 指導教師 高建 資訊科技與網路安全學院 2020年11月7日 netwo...