要用Python实现一个简单的爬虫功能,你可以使用requests库来获取网页内容,然后使用BeautifulSoup库来解析HTML并提取所需信息。以下是一个简单的示例,展示了如何实现一个基本的爬虫:
首先,确保已经安装了requests和beautifulsoup4库。如果没有安装,可以使用以下命令安装:
pip install requests beautifulsoup4
然后,创建一个名为simple_crawler.py
的Python文件,并添加以下代码:
import requests
from bs4 import BeautifulSoup
def get_html(url):
try:
response = requests.get(url)
response.raise_for_status()
return response.text
except requests.RequestException as e:
print(f"Error while fetching URL: {e}")
return None
def parse_html(html):
soup = BeautifulSoup(html, 'html.parser')
# 提取所需信息,例如标题
title = soup.title.string if soup.title else "No title found"
return title
def main():
url = input("Enter the URL of the webpage you want to crawl: ")
html = get_html(url)
if html:
title = parse_html(html)
print(f"Title of the webpage: {title}")
if __name__ == "__main__":
main()
这个简单的爬虫会获取用户输入的URL,然后使用requests库获取网页内容。接着,它使用BeautifulSoup解析HTML并提取页面标题。最后,它输出提取到的标题。
要运行这个简单的爬虫,只需在命令行中执行以下命令:
python simple_crawler.py
然后按照提示输入要爬取的网页URL。