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

相关推荐
@HNUSTer几秒前
Python数据可视化科技图表绘制系列教程(七)
python·数据可视化·科技论文·专业制图·科研图表
shizidushu2 分钟前
How to work with merged cells in Excel with `openpyxl` in Python?
python·microsoft·excel·openpyxl
eqwaak06 分钟前
科技信息差(9.13)
大数据·开发语言·人工智能·华为·语言模型
郝学胜-神的一滴10 分钟前
深入探索 Python 元组:从基础到高级应用
运维·服务器·开发语言·python·程序人生
一只乔哇噻14 分钟前
java后端工程师进修ing(研一版‖day44)
java·开发语言·学习·算法
技术程序猿华锋18 分钟前
深度解码OpenAI的2025野心:Codex重生与GPT-5 APIKey获取调用示例
人工智能·vscode·python·gpt·深度学习·编辑器
Ares-Wang33 分钟前
Vue3》》eslint Prettier husky
开发语言·javascript·ecmascript
EveryPossible1 小时前
静态箭头连线
开发语言·javascript·ecmascript
NiKo_W1 小时前
Git 版本回退与撤销修改
开发语言·git·安全
listhi5201 小时前
Map对象在JavaScript循环中的使用
开发语言·前端·javascript