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

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

相关推荐
上海云盾-小余1 小时前
全链路多层防护体系,一站式拦截 DDoS、CC、爬虫与注入攻击
网络·爬虫·安全·ddos
深蓝电商API1 天前
WebSocket 数据抓取原理与实践
爬虫
TlSfoward2 天前
抓包代理链路下的 TLS 指纹变化分析 TLSFOWARD抓包工具
数据库·爬虫·网络协议·搜索引擎·php
电商API_180079052472 天前
企业ERP进销存场景|京东商品详情接口自动同步方案|凭证鉴权批量调用技术实操
大数据·运维·人工智能·爬虫·数据挖掘·网络爬虫
拓海SEO外贸2 天前
Google 爬虫管理:抓取预算、404 与重定向
爬虫·搜索引擎·信息可视化·seo·跨境电商·独立站搭建·seo优化
深蓝电商API2 天前
浏览器缓存机制对爬虫有什么影响?
爬虫
Dontla2 天前
网站爬虫控制策略介绍(robots.txt、sitemap.xml、x-robots-tag、noindex、nofollow)网站索引
xml·爬虫·dubbo
Bright Data3 天前
DuckDuckGo 搜索爬取器
爬虫·serp·网页数据
去码头整点薯条ing3 天前
某当网登录滑块【协议+OCR】
爬虫·python·ocr
上海云盾-小余3 天前
中小站点防护避坑:低价高防服务存在的各类安全短板剖析
网络·爬虫·安全·ddos