抓取网站上的内容需要使用爬虫程序。下面是一个示例程序,可以搜索指定网站的指定目录下的关键词。

import requests
from bs4 import BeautifulSoup

# 指定要搜索的关键词和网站
keyword = 'python'
website = 'https://www.example.com'

# 指定要搜索的目录
directory = '/blog/'

# 发送HTTP请求,获取网页内容
url = website + directory
response = requests.get(url)
html = response.content

# 使用BeautifulSoup解析网页内容,并搜索关键词
soup = BeautifulSoup(html, 'html.parser')
results = soup.findAll(text=lambda text: text and keyword in text)

# 输出搜索结果
print('搜索结果:')
for result in results:
    print(result)

以上示例程序只能搜索指定目录下的内容,如果要搜索网站的整个内容,可以将directory设置为/

需要注意的是,爬虫程序需要遵守网站的爬虫协议,不要过度访问网站,以免被封禁IP。


原文地址: https://www.cveoy.top/t/topic/mmyT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录