如何使用 Beautiful Soup 爬取网页内容?

使用 Python 的 Beautiful Soup 库可以方便地爬取网页内容。首先,需要使用 Python 的 requests 库发送 HTTP 请求并获取网页内容,然后将网页内容传递给 Beautiful Soup 解析器进行解析。

下面是一个使用 Beautiful Soup 爬取网页内容的示例代码:

import requests
from bs4 import BeautifulSoup

# 发送 HTTP 请求并获取网页内容
response = requests.get('http://www.example.com')
html = response.text

# 使用 Beautiful Soup 解析网页内容
soup = BeautifulSoup(html, 'html.parser')

# 查找所有 p 标签的内容
for p in soup.find_all('p'):
    print(p.text)

在这段代码中,我们使用 requests 库发送 HTTP 请求并获取网页内容,然后使用 Beautiful Soup 解析器解析网页内容。接下来,我们使用 find_all() 方法查找所有 p 标签的内容,并打印出来。

除了 find_all() 方法,Beautiful Soup 还提供了很多其他方法来查找网页内容,比如 find() 方法可以查找第一个符合条件的元素,select() 方法可以使用 CSS 选择器来查找元素等。可以参考 Beautiful Soup 的文档了解更多信息。

猜你喜欢

转载自blog.csdn.net/alexwei2009/article/details/128577395