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

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

相关推荐
沙漠之主8 小时前
Python 教学设计资料:从入门到实战的完整课程方案
爬虫·python
深蓝电商API16 小时前
用YOLO训练验证码目标检测模型的全流程
爬虫·yolo·目标检测·目标跟踪
wuyk5552 天前
Python网络爬虫入门到实战 第02章:HTTP/HTTPS协议超通俗精讲(GET/POST、请求头、响应码、爬虫核心基础)
爬虫·python·http
szial2 天前
网络爬虫与 CDP 实战(二):浏览器能访问,Python 却被拒绝?拆开登录态与 CSRF
爬虫·python·csrf
梅雅达编程笔记3 天前
04-Python CSV数据保存与翻页抓取
开发语言·爬虫·python·pandas·数据采集·csv
梅雅达编程笔记3 天前
03_网页表格数据抓取
爬虫·python·beautifulsoup·pandas·数据采集
傻啦嘿哟3 天前
爬虫代理IP池从0到1:构建高可用代理池,彻底解决IP被封问题
网络·爬虫·tcp/ip
szial3 天前
网络爬虫与 CDP 实战(一):网页数据到底在哪?从 HTTP 到分页采集
网络·爬虫·python·网络爬虫
深蓝电商API3 天前
反检测浏览器(比特/AdsPower)原理剖析与自建替代方案
爬虫·反检测浏览器
深蓝电商API4 天前
Puppeteer vs Playwright:多维度压测后的选型建议
爬虫·puppeteer·playwright