使用网络爬虫简单爬取页面信息

这里展示的代码是将从网页获取的数据并转换为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中的属性值并同时写入。

相关推荐
电商API_1800790524719 小时前
构建高效可靠的电商 API:设计原则与实践指南
运维·服务器·爬虫·数据挖掘·网络爬虫
waterHBO1 天前
python 爬虫工具 mitmproxy, 几问几答,记录一下
开发语言·爬虫·python
武子康2 天前
AI炼丹日志-28 - Audiblez 将你的电子书epub转换为音频mp3 做有声书
人工智能·爬虫·gpt·算法·机器学习·ai·音视频
AIGC_北苏2 天前
DrissionPage爬虫包实战分享
爬虫·python·drissionpage
华科云商xiao徐2 天前
增量式网络爬虫通用模板
爬虫
仟濹2 天前
「数据分析 - Pandas 函数」【数据分析全栈攻略:爬虫+处理+可视化+报告】
爬虫·数据分析·pandas
爬虫程序猿2 天前
利用 Python 爬虫获取淘宝商品详情
开发语言·爬虫·python
FAQEW2 天前
爬虫的几种方式(使用什么技术来进行一个爬取数据)
爬虫·python
cooldream20092 天前
利用 Scrapy 构建高效网页爬虫:框架解析与实战流程
爬虫·scrapy·架构
Dxy12393102163 天前
DrissionPage调试工具:网页自动化与数据采集的革新利器
爬虫·python·drissionpage