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

相关推荐
m0_495496418 分钟前
SQL批量更新状态机字段_使用CASE表达式一次性处理
jvm·数据库·python
2401_850491659 分钟前
Python处理分类不平衡问题_使用平衡随机森林提升召回率
jvm·数据库·python
终生成长者17 分钟前
04LangChain SQL 问答系统知识点详解
数据库·python·sql·langchain
m0_7335654621 分钟前
Golang Redis Pipeline如何用_Golang Redis Pipeline教程【完整】
jvm·数据库·python
admiraldeworm22 分钟前
c -> true 导致异常返回 404 问题排查
c语言·开发语言
翎刿30 分钟前
AttributeError: ‘FigureCanvasInterAgg‘
python
2401_8676239831 分钟前
golang如何实现布隆过滤器_golang布隆过滤器实现教程
jvm·数据库·python
m0_7407963633 分钟前
golang如何编写Markdown转HTML工具_golang Markdown转HTML工具编写详解
jvm·数据库·python
2403_8832610936 分钟前
CSS如何实现Bootstrap进度条自定义动画_利用keyframe关键帧
jvm·数据库·python
2301_7693406737 分钟前
CSS如何兼容新旧方案结合响应式容器查询
jvm·数据库·python