网络爬虫-Python网络爬虫和C#网络爬虫

embedded/2024/10/25 6:30:29/

爬虫是一种从互联网抓取数据信息的自动化程序,通过 HTTP 协议向网站发送请求,获取网页内容,并通过分析网页内容来抓取和存储网页数据。爬虫可以在抓取过程中进行各种异常处理、错误重试等操作,确保爬取持续高效地运行

1、Python网络爬虫

Python 网络爬虫详细介绍
Python网络爬虫是自动化程序,用来抓取网页上的数据。通过网络爬虫,你可以从互联网上采集、处理数据,比如抓取产品信息、新闻内容等。Python因其丰富的库和强大的生态系统,非常适合构建网络爬虫。下面详细介绍Python爬虫的基本流程、常用库、反爬机制以及如何处理爬虫数据。

1. Python 爬虫基本流程

网络爬虫的工作流程主要包括以下步骤:

发送请求:向目标网站发起请求(GET/POST),获取网页内容。
获取响应:服务器返回HTML或JSON等格式的数据。
解析网页:将获取到的网页内容解析,提取目标数据。
数据存储:将提取到的数据保存到文件或数据库中。
递归抓取:如果需要,可以根据页面的链接继续递归抓取其他页面。

2. Python 常用爬虫

Python有多个用于实现网络爬虫的库,以下几个最常用的库是构建爬虫的基础。

(1) Requests 库

Requests是一个简单高效的HTTP库,能够发出请求并接收响应,支持GET、POST等常见的请求方式。

安装 Requests:

pip install requests

基本使用:

import requestsresponse = requests.get('https://example.com')
if response.status_code == 200:print(response.text)  # 打印网页HTML内容

(2) BeautifulSoup 库

BeautifulSoup是一个用于解析HTML/XML的库,能够方便地从网页中提取数据。它可以和Requests一起使用,解析网页内容。

安装 BeautifulSoup:

pip install beautifulsoup4

解析网页内容:

from bs4 import BeautifulSoup
import requestsresponse = requests.get('https://example.com')
soup = BeautifulSoup(response.text, 'html.parser')# 获取网页标题
title = soup.title.string
print(f"网页标题: {title}")# 提取所有链接
links = soup.find_all('a')
for link in links:print(link.get('href'))

(3) lxml 库

lxml是一个性能极佳的HTML/XML解析库,能够快速解析和处理大量网页内容。

安装 lxml:

pip install lxml

使用示例:

from lxml import etree
import requestsresponse = requests.get('https://example.com')
tree = etree.HTML(response.content)# 提取所有链接
links = tree.xpath('//a/@href')
print(links)

(4) Scrapy 爬虫框架

Scrapy是Python最强大的爬虫框架,适用于大型爬虫项目。它支持异步下载、多线程爬取、自动处理链接追踪等。

安装 Scrapy:

pip install scrapy

创建 Scrapy 项目:

scrapy startproject myproject

基本爬虫

i

mport scrapyclass ExampleSpider(scrapy.Spider):name = 'example'start_urls = ['https://example.com']def parse(self, response):for title in response.css('title::text'):yield {'title': title.get()}

3. 反爬机制及其应对

很多网站会有反爬机制,常见的反爬措施有:

IP封禁:频繁请求可能导致IP封禁。
User-Agent 检测:服务器会检查请求头是否为真实浏览器发出的请求。
验证码:通过验证码防止自动化请求。
动态加载内容:使用JavaScript动态加载内容。
应对措施:

设置请求头:通过设置 User-Agent 模拟浏览器访问。
使用代理:通过代理IP避免频繁访问被封禁。
模拟浏览器行为:使用 Selenium 等工具来处理动态加载的内容。
自动识别验证码:使用 OCR 工具(如Tesseract)识别验证码。
设置User-Agent示例:

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get('https://example.com', headers=headers)

使用Selenium处理动态内容:

from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://example.com')html = driver.page_source
print(html)
driver.quit()

4. 数据存储

抓取到的数据可以存储为文件或写入数据库。

保存为CSV文件:

import csvwith open('data.csv', mode='w') as file:writer = csv.writer(file)writer.writerow(['Name', 'URL'])writer.writerow(['Example', 'https://example.com'])

存储到数据库:

import pymysqlconn = pymysql.connect(host='localhost', user='user', password='password', db='database')
cursor = conn.cursor()cursor.execute("INSERT INTO table_name (name, url) VALUES (%s, %s)", ('Example', 'https://example.com'))
conn.commit()
conn.close()

C# 网络爬虫详细介绍

C# 也可以用于网络爬虫开发,通过 HTTP 请求获取网页数据并进行解析。与 Python 类似,C# 也有相应的库和框架,虽然 C# 网络爬虫在简便性和灵活性上不如 Python,但在某些企业级应用中,C# 也表现出色。

1. C# 爬虫的基本流程

与 Python 爬虫类似,C# 网络爬虫的基本流程如下:

发送HTTP请求:使用 HttpClient 发送 GET/POST 请求。
获取网页响应:获取网页内容(HTML)。
解析HTML内容:使用正则表达式或 HTML 解析库。
提取并存储数据:提取有用数据,保存到文件或数据库。

2. 常用库

(1) HttpClient

HttpClient 是用于发送 HTTP 请求的 .NET 类,能够轻松地与网页进行交互。

示例代码:

using System;
using System.Net.Http;
using System.Threading.Tasks;class Program
{static async Task Main(string[] args){using (HttpClient client = new HttpClient()){HttpResponseMessage response = await client.GetAsync("https://example.com");string result = await response.Content.ReadAsStringAsync();Console.WriteLine(result);}}
}

(2) HtmlAgilityPack

HtmlAgilityPack 是 C# 的 HTML 解析库,能够方便地从 HTML 中提取数据,类似于 Python 的 BeautifulSoup。

  • 安装 HtmlAgilityPack:
Install-Package HtmlAgilityPack
  • 解析 HTML 并提取数据:
using HtmlAgilityPack;
using System;class Program
{static void Main(string[] args){var url = "https://example.com";HtmlWeb web = new HtmlWeb();var htmlDoc = web.Load(url);var title = htmlDoc.DocumentNode.SelectSingleNode("//title").InnerText;Console.WriteLine("标题: " + title);var links = htmlDoc.DocumentNode.SelectNodes("//a[@href]");foreach (var link in links){Console.WriteLine(link.GetAttributeValue("href", string.Empty));}}
}

(3) 正则表达式

C# 提供了强大的正则表达式库来从网页内容中提取数据。

示例代码:

using System;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;class Program
{static async Task Main(string[] args){using (HttpClient client = new HttpClient()){string content = await client.GetStringAsync("https://example.com");// 使用正则表达式提取所有链接Regex regex = new Regex(@"href=""(.*?)""");MatchCollection matches = regex.Matches(content);foreach (Match match in matches){Console.WriteLine(match.Groups[1].Value);}}}
}

3. 反爬机制应对

与 Python 类似,C# 网络爬虫也需要应对反爬机制。通过设置请求头和使用代理,可以避免被网站封禁。

  • 设置User-Agent:
using System;
using System.Net.Http;class Program
{static async Task Main(string[] args){HttpClientHandler handler = new HttpClientHandler();using (HttpClient client = new HttpClient(handler)){client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");HttpResponseMessage response = await client.GetAsync("https://example.com");string result = await response.Content.ReadAsStringAsync();Console.WriteLine(result);}}
}
  • 使用代理:
HttpClientHandler handler = new HttpClientHandler
{Proxy = new WebProxy("http://yourproxy:8080", true),UseProxy = true
};

4. 数据存储

在 C# 爬虫中,数据可以被保存到文件、数据库等存储方式。

保存为文件:

using System;
using System.IO;class Program
{static void Main(string[] args){string data = "爬虫抓取的数据";File.WriteAllText("data.txt", data);}
}
  • 存储到数据库(SQL Server):
using System;
using System.Data.SqlClient;class Program
{static void Main(string[] args){string connectionString = "Data Source=.;Initial Catalog=myDatabase;Integrated Security=True";using (SqlConnection conn = new SqlConnection(connectionString)){conn.Open();string query = "INSERT INTO WebData (Title, Url) VALUES (@Title, @Url)";using (SqlCommand cmd = new SqlCommand(query, conn)){cmd.Parameters.AddWithValue("@Title", "Example");cmd.Parameters.AddWithValue("@Url", "https://example.com");cmd.ExecuteNonQuery();}}}
}

http://www.ppmy.cn/embedded/132265.html

相关文章

平安养老险深圳分公司:创新养老服务,深入践行金融为民

党的二十届三中全会《决定》提出:“积极发展科技金融、绿色金融、普惠金融、养老金融、数字金融,加强对重大战略、重点领域、薄弱环节的优质金融服务。” 为经济社会发展提供高质量服务,更好满足人民日益增长的美好生活需要,金融…

ubuntu下快捷键启动程序

背景:公司自开发的软件,经常需要启动,每次去找目录启动很麻烦,所以想快捷启动 方法1: 通过编辑.baserc启动 例如启动程序是toolA, 放在/home/user/software/目录下,那么在~/.baserc里面加入一行代码 al…

Linux的例行性工作1

[rootserver ~]# vim test2.sh //编辑脚本 1、每分钟执行命令 [rootserver ~]# crontab -e [rootserver ~]# crontab -l* * * * * sh /root/test2.sh[rootserver ~]# ls anaconda-ks.cfg cro.txt dead.letter test2.sh testcrondtab.sh [rootserver ~]# cat cro.txt…

7、基于爬虫+Flask+Echarts+MySQL的网易云评论可视化大屏

基于爬虫FlaskEchartsMySQL的网易云评论可视化大屏 1、前言2、实现2.1 挑选想要采集的歌曲评论2.2 构建爬虫2.2.1 采集歌曲评论2.2.2 清洗数据入库 2.3 搭建flask框架2.4 数据传值2.5 完整代码&数据集获取 1、前言 本项目是基于requests爬虫flaskecharts搭建的网易云评论的…

Pandas 文件读取与保存指南:高效处理 CSV、Excel 等多种格式数据

Pandas 文件读取与保存指南:高效处理 CSV、Excel 等多种格式数据 本文详细介绍了如何使用 Pandas 的 IO 工具从各种常见文件格式(如 CSV、Excel、HTML、TXT 等)中读取和保存数据。通过 Pandas,用户可以轻松读取和修改数据&#x…

Java-线程池技术

一、线程池简介 线程池是一种池化的思想,是将一些共同资源放到池中进行管理和使用,从而避免大量的创建销毁带来的资源浪费等问题,线程池主要优点体现在: 降低资源消耗:普通线程创建执行完任务之后即被销毁&#xff0…

阿里云用STS上传oss的完整程序执行流程图 和前端需要哪些参数uniapp

H5 微信小程序可用的前端直传阿里云OSS(STS临时凭证前端签名)直接下载插件 下面是原理说明: 明白了,我来详细说明前端上传文件到阿里云OSS需要携带的具体参数: 从服务器获取的 STS 凭证: // 这些参数需要从你的后端服务器获…

从0开始学python-day14-pandas1

一、基础 1、概述 Pandas 是一个开源的第三方 Python 库,从 Numpy 和 Matplotlib 的基础上构建而来 Pandas 名字衍生自术语 "panel data"(面板数据)和 "Python data analysis"(Python 数据分析)…