少于 1 分钟阅读

PS: 主要为 requests + BeautifulSoup 的爬虫实现

使用 Requests 获取网站的 HTML

import requests
# 请求头,用户代理,反爬虫突破
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}

# 获取响应码 一般为 200
response = requests.get(url, headers=headers)

if response.ok:
    print(response.text)
else:
    print("请求失败")

使用 BeautifulSoup 方便标签的查找

import requests
from bs4 import BeautifulSoup

content = requests.get("url").text
# 将 HTML 文件转换为 目录树状图
soup = BeautifulSoup(content, "html.parser")

# 查找树状图下全部标签 h3 中的内容
all_titles = soup.find_all("h3")

# 在整个 HTML 网页中,找出所有带有 class="title" 属性的 <span> 标签
all_titles = soup.find_all("span", attrs={"class": "title"})

找到 豆瓣top250 代码示例

import requests
from bs4 import BeautifulSoup

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}

for start_num in range(0, 250, 25):
    response = requests.get(f'https://movie.douban.com/top250?start={start_num}', headers=headers)
    html = response.text
    soup = BeautifulSoup(html, 'html.parser')
    all_titles = soup.find_all("span", attrs={"class": "title"})
    for title in all_titles:
        title_string = title.string
        if "/" not in title_string:
            print(title_string)