创建一个简单的Python 3.7爬虫,你可以使用`requests`库来发送HTTP请求,以及`BeautifulSoup`库来解析HTML内容。以下是一个基本的示例,展示了如何爬取一个网站上的标题、描述和链接信息,并将这些数据保存到CSV文件中:
import requestsfrom bs4 import BeautifulSoupimport csv目标网站的URLurl = 'https://example.com'发送HTTP请求response = requests.get(url)检查请求是否成功if response.status_code == 200:解析HTML内容soup = BeautifulSoup(response.text, 'html.parser')提取所需信息titles = [tag.text for tag in soup.find_all('h1')]descriptions = [tag.text for tag in soup.find_all('p')]links = [tag['href'] for tag in soup.find_all('a', href=True)]将数据保存到CSV文件with open('output.csv', mode='w', newline='', encoding='utf-8') as file:writer = csv.writer(file)writer.writerow(['Title', 'Description', 'Link'])for title, description, link in zip(titles, descriptions, links):writer.writerow([title, description, link])else:print(f'Failed to retrieve the webpage. Status code: {response.status_code}')
请确保在运行此代码之前已经安装了`requests`和`beautifulsoup4`库。如果尚未安装,可以使用以下命令进行安装:
pip install requests beautifulsoup4
此代码示例适用于爬取具有标准HTML结构的网站。对于更复杂的网站,可能需要使用更高级的解析技巧或第三方库,如`Scrapy`。

