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

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

相关推荐
zhougl99613 小时前
Java Spring Boot 爬虫技术全面介绍
java·spring boot·爬虫
Cory.眼13 小时前
Python爬虫实战:从入门到进阶
开发语言·爬虫·python
python布道者051614 小时前
【技术分享】从零构建YouTube评论爬虫:TKinter + Pandas + 反反爬全解析
爬虫·youtube
zhougl99619 小时前
Java实现腾讯云开发者社区列表爬虫
java·爬虫·腾讯云
Experience-摆渡2 天前
Firecrawl深度调研报告:功能、实现原理、架构与自研落地建议
爬虫
深蓝电商API2 天前
Hook XMLHttpRequest 实战
爬虫·hook
quantdash_cc2 天前
告别自建 Requests/BS4 网页爬虫:基于 QuantDash 搭建零维保的高性能量化行情流水线
开发语言·爬虫·python·pandas·量化·quantdash
Patrick在香港3 天前
Python爬虫框架实战:优雅抓取香港政府公开API数据的通用方案
java·开发语言·爬虫·python·ai编程·数据可视化·可用性测试
鬼手点金4 天前
与LLM结合的主流智能爬虫框架
爬虫·python·llm·post·request·firecrawl·crawl4ai