搜索
首页后端开发Python教程Python爬虫技术入门实例代码解析

爬虫技术基础概念

  1. 爬虫:自动获取网络数据的程序。

  2. Web页面结构:HTML、CSS、JavaScript等。

  3. HTTP请求:客户端向服务器请求数据的方式。

  4. HTTP响应:服务器返回给客户端的数据。

请求与响应

使用Python的requests库发送HTTP请求。

import requests
 
url = "https://www.example.com"
response = requests.get(url)

获取响应内容

html_content = response.text

HTML解析与数据提取

使用BeautifulSoup库解析HTML内容。

from bs4 import BeautifulSoup
 
soup = BeautifulSoup(html_content, "html.parser")

使用CSS选择器或其他方法提取数据。

title = soup.title.string

实战:爬取简书网站首页文章信息

发送请求,获取简书网站首页HTML内容。

import requests
from bs4 import BeautifulSoup
 
url = "https://www.jianshu.com"
response = requests.get(url)
html_content = response.text

存储数据

将数据存储为JSON格式。

import json
 
with open("jianshu_articles.json", "w", encoding="utf-8") as f:
    json.dump(article_info_list, f, ensure_ascii=False, indent=4)

测试与优化

1.遇到反爬虫策略时,可以使用User-Agent伪装成浏览器。

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
response = requests.get(url, headers=headers)

2.使用time.sleep()函数控制请求频率。

import time
 
time.sleep(10)

3.错误处理与异常捕获。

try:
    response = requests.get(url, headers=headers, timeout=5)
    response.raise_for_status()
except requests.exceptions.RequestException as e:
    print(f"Error: {e}")

网站爬虫完整代码:

import requests
from bs4 import BeautifulSoup
import json
import time
 
def fetch_jianshu_articles():
    url = "https://www.jianshu.com"
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
 
    try:
        response = requests.get(url, headers=headers, timeout=5)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        print(f"Error: {e}")
        return
 
    html_content = response.text
    soup = BeautifulSoup(html_content, "html.parser")
    articles = soup.find_all("div", class_="content")
    article_info_list = []
 
    for article in articles:
        title = article.h3.text.strip()
        author = article.find("span", class_="name").text.strip()
        link = url + article.h3.a["href"]
 
        article_info = {"title": title, "author": author, "link": link}
        article_info_list.append(article_info)
 
    return article_info_list
 
def save_to_json(article_info_list, filename):
    with open(filename, "w", encoding="utf-8") as f:
        json.dump(article_info_list, f, ensure_ascii=False, indent=4)
 
if __name__ == "__main__":
    article_info_list = fetch_jianshu_articles()
    if article_info_list:
        save_to_json(article_info_list, "jianshu_articles.json")
        print("Jianshu articles saved to 'jianshu_articles.json'.")
    else:
        print("Failed to fetch Jianshu articles.")

补充

为了更好地理解这个实战项目,我们需要了解一些基础概念和原理,这将有助于掌握Python的网络编程和爬虫技术。以下是一些基本的网络爬虫概念:

  1. HTTP协议:超文本传输协议(HTTP)是一种用于传输超媒体文档(如 HTML)的应用层协议。HTTP协议被用于从Web服务器传输或发布到Web浏览器或其他客户端的数据。

  2. HTML、CSS 和 JavaScript:HTML 是用来描述网页的一种语言。CSS 是用来表现 HTML 结构的样式。JavaScript 是网页编程的一种脚本语言,主要用于实现网页上的动态效果和与用户的交互。

  3. DOM:文档对象模型(DOM)是一种跨平台的编程接口,用于处理 HTML 和 XML 文档。DOM将文档视为树形结构,其中每个节点代表一个部分(如元素、属性或文本)。

  4. URL:统一资源定位符(URL)是用于指定互联网资源位置的一种字符串。

  5. 请求头(Request Headers):在HTTP请求中,请求头包含了关于客户端的环境、浏览器等信息。常见的请求头字段有:User-Agent、Accept、Referer 等。

  6. 响应头(Response Headers):在HTTP响应中,响应头包含了关于服务器的信息、响应状态码等信息。常见的响应头字段有:Content-Type、Content-Length、Server 等。

  7. 网络爬虫策略:有些网站会采取一些策略来阻止爬虫抓取数据,如:封禁IP、限制访问速度、使用 JavaScript 动态加载数据等。在实际应用中,我们需要根据这些策略采取相应的应对措施,如:使用代理IP、限制爬虫抓取速度、使用浏览器模拟库(如 Selenium)等。

以上是Python爬虫技术入门实例代码解析的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:亿速云。如有侵权,请联系admin@php.cn删除
Python是否列表动态阵列或引擎盖下的链接列表?Python是否列表动态阵列或引擎盖下的链接列表?May 07, 2025 am 12:16 AM

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他们areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

如何从python列表中删除元素?如何从python列表中删除元素?May 07, 2025 am 12:15 AM

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)删除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

试图运行脚本时,应该检查是否会遇到'权限拒绝”错误?试图运行脚本时,应该检查是否会遇到'权限拒绝”错误?May 07, 2025 am 12:12 AM

toresolvea“ dermissionded”错误Whenrunningascript,跟随台词:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。

与Python的图像处理中如何使用阵列?与Python的图像处理中如何使用阵列?May 07, 2025 am 12:04 AM

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

对于哪些类型的操作,阵列比列表要快得多?对于哪些类型的操作,阵列比列表要快得多?May 07, 2025 am 12:01 AM

ArraySaresificatificallyfasterthanlistsForoperationsBenefiting fromDirectMemoryAcccccccCesandFixed-Sizestructures.1)conscessingElements:arraysprovideconstant-timeaccessduetocontoconcotigunmorystorage.2)iteration:araysleveragececacelocality.3)

说明列表和数组之间元素操作的性能差异。说明列表和数组之间元素操作的性能差异。May 06, 2025 am 12:15 AM

ArraySareBetterForlement-WiseOperationsDuetofasterAccessCessCessCessCessCessAndOptimizedImplementations.1)ArrayshaveContiguucuulmemoryfordirectAccesscess.2)列出sareflexible butslible dueTopotentEnallymideNamicizing.3)forlarargedAtaTasetsetsetsetsetsetsetsetsetsetsetlib

如何有效地对整个Numpy阵列进行数学操作?如何有效地对整个Numpy阵列进行数学操作?May 06, 2025 am 12:15 AM

在NumPy中进行整个数组的数学运算可以通过向量化操作高效实现。 1)使用简单运算符如加法(arr 2)可对数组进行运算。 2)NumPy使用C语言底层库,提升了运算速度。 3)可以进行乘法、除法、指数等复杂运算。 4)需注意广播操作,确保数组形状兼容。 5)使用NumPy函数如np.sum()能显着提高性能。

您如何将元素插入python数组中?您如何将元素插入python数组中?May 06, 2025 am 12:14 AM

在Python中,向列表插入元素有两种主要方法:1)使用insert(index,value)方法,可以在指定索引处插入元素,但在大列表开头插入效率低;2)使用append(value)方法,在列表末尾添加元素,效率高。对于大列表,建议使用append()或考虑使用deque或NumPy数组来优化性能。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。