python最简单的爬虫代码

python
import requests from bs4 import BeautifulSoup # 要爬取的网页地址 url = 'https://example.com' # 发送GET请求获取网页内容 response = requests.get(url) # 确保请求成功 if response.status_code == 200: # 使用BeautifulSoup解析HTML soup = BeautifulSoup(response.text, 'html.parser') # 在这里编写获取和处理数据的代码 # 例如,查找所有的链接 links = soup.find_all('a') # 打印链接 for link in links: print(link.get('href')) else: print('Failed to retrieve the webpage')

这段代码首先发送GET请求到指定的网址,然后使用BeautifulSoup解析返回的HTML内容。您可以在解析后的HTML中进行任何所需的操作,比如查找特定标签、提取数据等。在这个例子中,它简单地查找并打印了页面中的所有链接。

python
import requests from bs4 import BeautifulSoup def save_links_to_file(links, filename='links.txt'): """将链接保存到文件中""" with open(filename, 'w') as file: for link in links: file.write(link.get('href') + '\n') def simple_web_crawler(url): """简单的网络爬虫""" try: # 发送GET请求获取网页内容 response = requests.get(url) # 确保请求成功 if response.status_code == 200: # 使用BeautifulSoup解析HTML soup = BeautifulSoup(response.text, 'html.parser') # 查找所有的链接 links = soup.find_all('a') # 保存链接到文件中 save_links_to_file(links) # 打印链接 for link in links: print(link.get('href')) else: print('Failed to retrieve the webpage') except Exception as e: print('An error occurred:', e) if __name__ == "__main__": # 要爬取的网页地址 url = 'https://example.com' simple_web_crawler(url)

在这个版本中,我添加了一个函数save_links_to_file来将爬取到的链接保存到文件中。另外,我还将整个爬虫包装在一个try-except块中,以处理可能发生的异常情况,比如网络连接问题或者解析HTML时的错误。这样能够提高程序的健壮性,避免因为一些不可控因素导致程序崩溃。