以下是使用BeautifulSoup库进行网页抓取的Python代码示例:
from bs4 import BeautifulSoup
import requests
# 发送GET请求获取网页内容
url = 'http://example.com'
response = requests.get(url)
html_content = response.text
# 创建BeautifulSoup对象,解析网页内容
soup = BeautifulSoup(html_content, 'html.parser')
# 找到所有的标签并打印链接文本
for link in soup.find_all('a'):
print(link.get('href'))
以上代码首先使用requests库发送GET请求获取网页内容,然后使用BeautifulSoup库创建一个BeautifulSoup对象来解析网页内容。接下来,使用find_all
方法找到所有的标签,并使用
get
方法获取链接文本并打印出来。
请注意,这只是一个简单的示例。实际应用中,您可能需要使用更多的BeautifulSoup方法来定位和提取您需要的内容。