爬虫python案例2
下面是一个简单的爬虫案例,可以爬取糗事百科的段子,并将段子的内容和作者输出到控制台。
首先,需要安装 requests 和 BeautifulSoup 这两个库。在命令行中输入以下命令:
Copy code
pip install requests
pip install beautifulsoup4
安装完成后,可以开始编写代码。以下是代码示例:
pythonCopy code
import requestsfrom bs4 import BeautifulSoup
url = 'https://www.qiushibaike.com/text/'response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
articles = soup.find_all('div', class_='article')for article in articles:
content = article.find('div', class_='content').get_text(strip=True)
author = article.find('div', class_='author').find('h2').get_text(strip=True) print(f'{author}: {content}\n')
代码的思路是,首先通过 requests 库向糗事百科的段子页面发起请求,获取页面的 HTML 代码。然后,使用 BeautifulSoup 库解析 HTML 代码,找到包含段子信息的 div 标签,提取出其中的段子内容和作者信息,最后输出到控制台。
当然,这只是一个简单的爬虫案例,实际的爬虫可能需要更复杂的处理逻辑和数据存储方式。