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、测试

相关推荐
常常有1 分钟前
AI智能知识库问答系统(基于 FastAPI和Dify)
python·mysql·fastapi
CLX05053 分钟前
CSS如何制作响应式图片集布局_利用object-fit填充空间
jvm·数据库·python
Achou.Wang4 分钟前
Go语言并发编程中的死锁防范与破解之道
服务器·开发语言·golang
我命由我123456 分钟前
Visual Studio - Visual Studio 注释快捷键
java·c语言·开发语言·c++·ide·java-ee·visual studio
子安柠7 分钟前
深入理解 Go 反射:原理、实践与性能陷阱
开发语言·golang
yoyo_zzm10 分钟前
ThinkPHP3.X:经典PHP框架的全面解析
开发语言·php
平常心cyk10 分钟前
Dify和Function Calling(函数调用)简介
python
lemon_sjdk13 分钟前
DecimalFormat
java·开发语言·python
2303_8212873813 分钟前
SQL如何进行分组后字符串拼接_使用GROUP_CONCAT或STRING_AGG
jvm·数据库·python
小哈蒙德16 分钟前
基于deepSeekV4Pro(thinking)研究pointPillar的历程
python·算法