# Python爬虫代码完整版
import requests
from bs4 import BeautifulSoup
# 定义一个函数,用于获取网页内容
def get_html(url):
try:
# 发送HTTP请求
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
return response.text
else:
print(f"请求失败,状态码: {response.status_code}")
return None
except Exception as e:
print(f"请求过程中出现错误: {e}")
return None
# 定义一个函数,用于解析网页内容
def parse_html(html):
soup = BeautifulSoup(html, 'html.parser')
# 假设我们要提取所有的标题标签<h1>
titles = soup.find_all('h1')
for title in titles:
print(title.get_text())
# 主函数
def main():
url = 'https://example.com' # 替换为你想要爬取的网址
html = get_html(url)
if html:
parse_html(html)
if __name__ == '__main__':
main()
导入库:
requests
:用于发送HTTP请求。BeautifulSoup
:用于解析HTML内容。get_html 函数:
None
。parse_html 函数:
<h1>
标签,并打印其文本内容。main 函数:
get_html
函数获取HTML内容。parse_html
函数解析并处理HTML内容。程序入口:
main
函数执行爬虫任务。上一篇:python break
下一篇:args在python中的含义
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站