# 示例代码:Python 实战 - 简单的爬虫程序
import requests
from bs4 import BeautifulSoup
def fetch_website_data(url):
"""
这个函数用于获取网页内容。
参数:
url (str): 要抓取的网页链接
返回:
str: 网页的HTML内容,如果请求失败则返回None
"""
try:
response = requests.get(url)
response.raise_for_status() # 检查请求是否成功
return response.text
except requests.RequestException as e:
print(f"请求出错: {e}")
return None
def parse_html(html_content):
"""
解析HTML内容,提取所需信息。
参数:
html_content (str): HTML内容
返回:
list: 提取的信息列表
"""
if not html_content:
return []
soup = BeautifulSoup(html_content, 'html.parser')
titles = soup.find_all('h2') # 假设我们要提取所有的<h2>标签中的文本
return [title.get_text() for title in titles]
if __name__ == "__main__":
url = "https://example.com"
html_content = fetch_website_data(url)
data = parse_html(html_content)
print(data)
fetch_website_data 函数:该函数使用 requests 库来获取指定 URL 的网页内容。如果请求成功,则返回网页的 HTML 内容;如果请求失败,则捕获异常并返回 None。
parse_html 函数:该函数使用 BeautifulSoup 来解析 HTML 内容,并提取所有 <h2> 标签中的文本。你可以根据需要修改这个部分以提取其他类型的数据。
主程序:在主程序中,我们定义了一个 URL 并调用上述两个函数来获取和解析网页内容,最后打印提取到的数据。
这个示例展示了如何使用 Python 进行简单的网页抓取和数据解析。你可以根据实际需求修改 URL 和解析逻辑。
上一篇:python i++
下一篇:python 异或
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站