python(一)网络爬取

在爬取网页信息时,需要注意网页爬虫规范文件robots.txt

eg:csdn的爬虫规范文件 csdn.net/robots.txt

User-agent:

下面的Disallow规则适用于所有爬虫(即所有用户代理)。星号*是一个通配符,表示"所有"。

Disallow:

禁止爬虫访问的路径

1、首先下载python的相关类库

python 复制代码
pip install requests
pip install beautifulsoup4

requests 是一个http库,可以发送网络请求 。

beautifulsoup4 主要用来解析html文档。

2、引入相关库

python 复制代码
import requests    
from bs4 import BeautifulSoup  

3、编写相关代码

python 复制代码
url = 'https://www.....com'    
response = requests.get(url)    
  
html_content = response.text  
soup = BeautifulSoup(html_content, 'html.parser')  
  
titles = soup.select('h2') 
for title in titles:  
    print(title.text)

url : 需要爬的页面路径

response = requests.get(url) 发送get请求并接受

html_content = response.text 取出页面主体

soup = BeautifulSoup(html_content, 'html.parser') 由beautifulsoup对主体中的h5标签解析

titles = soup.select('h2') 选择所有的h2标签

最后循环遍历打印出所有h2 标签

4、测试

相关推荐
阿闽ooo4 分钟前
单例模式深度解析:从饿汉到懒汉的实战演进
开发语言·c++·笔记·设计模式
爱喝水的鱼丶4 分钟前
SAP-ABAP:通过接口创建生产订单报“没有工艺路线选中”错误解决办法详解
运维·开发语言·sap·abap·bapi·生产订单
x70x809 分钟前
C++中auto的使用
开发语言·数据结构·c++·算法·深度优先
Han.miracle12 分钟前
数据结构与算法-012
java·开发语言
计算机毕设指导617 分钟前
基于微信小程序+django连锁火锅智慧餐饮管理系统【源码文末联系】
java·后端·python·mysql·微信小程序·小程序·django
colourmind17 分钟前
记录一次vscode debug conda python 使用报错问题排查
vscode·python·conda
智航GIS21 分钟前
2.1 变量与数据类型
开发语言·python
旧梦吟22 分钟前
脚本工具 批量md转html
前端·python·html5
拼好饭和她皆失26 分钟前
c++---快速记忆stl容器
开发语言·c++