这里展示的代码是将从网页获取的数据并转换为csv文件的示例。
import csv
import requests
import json
def get_direction(id):
headers2 = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"}
param = {'id': f'{id}'}
url2 = "https://onquadro.cs.put.poznan.pl/api/Tetrad/GetListOfTetrads"
response2 = requests.get(url2, params=param, headers=headers2)
data = response2.json()
direction_value = data[0]['direction']
return direction_value
#向url请求数据并获取响应数据
headers={
"user-agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"
}
url="https://onquadro.cs.put.poznan.pl/api/Quadruplex/GetQuadruplexes"
response=requests.get(url,headers=headers)
#将响应数据转换为python对象
datas = json.loads(response.text)
# 定义 CSV 文件的列名
fieldnames = [
"id", "pdbId", "pdbDeposition", "assemblyId", "molecule", "experiment",
"sequence", "ion", "ion_charge", "typeOfStrands", "type", "onzmClass",
"numberOfTetrads", "loopTopology", "tetradCombination", "direction"
]
# 打开 CSV 文件并写入数据
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
# 写入表头
writer.writeheader()
# 遍历数据并写入每一行
for item in datas:
item['direction']=get_direction(item['id'])
writer.writerow(item)
print("数据已成功写入 CSV 文件 'output.csv'")
由于我要获取的数据存在于多个url(一个涵盖所有条数据的url以及每条数据单独属性的url),所以在将url1(涵盖所有条数据的url)中获取到的响应数据写入的过程中去单独获取了属于该条数据在url2中的属性值并同时写入。