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

相关推荐
IT_阿水14 小时前
C语言之printf函数用法
c语言·开发语言·printf
吃好喝好玩好睡好14 小时前
OpenHarmony混合开发实战指南
c语言·python·flutter·vr·visual studio
laocooon52385788614 小时前
C语言,少了&为什么报 SegmentationFault
c语言·开发语言
white-persist14 小时前
【攻防世界】reverse | re1-100 详细题解 WP
c语言·开发语言·网络·汇编·python·算法·网络安全
CHANG_THE_WORLD14 小时前
Python 中的循环结构详解
开发语言·python·c#
程序员-周李斌14 小时前
ConcurrentHashMap 源码分析
java·开发语言·哈希算法·散列表·开源软件
JS_GGbond14 小时前
JavaScript入门学习路线图
开发语言·javascript·学习
quikai198114 小时前
python练习第一组
开发语言·python
BD_Marathon14 小时前
【JavaWeb】JS_JSON在客户端的使用
开发语言·javascript·json
还没想好取啥名14 小时前
C++11新特性(一)——原始字面量
开发语言·c++