macos 使用vscode 开发python 爬虫(开发二)

以下是一个示例,用于爬取一个公开的示例网站(http://books.toscrape.com),并提取书籍的标题和价格:

python 复制代码
import requests
from bs4 import BeautifulSoup

# 发起请求并获取网页内容
url = '可以用上面的链接🔗'
response = requests.get(url)
html_content = response.text

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

# 提取书籍标题和价格
books = soup.find_all('article', class_='product_pod')

for book in books:
    title = book.h3.a['title']
    price = book.find('p', class_='price_color').text

    print('书名:', title)
    print('价格:', price)
    print('---')

这个示例使用了一个公开的书籍网站(http://books.toscrape.com),通过发送HTTP请求获取网页内容,并使用BeautifulSoup解析网页内容。然后,它找到所有的书籍信息,并提取书名和价格,并将它们打印出来。

运行脚本

powershell 复制代码
python spider.py

请确保你已经安装了所需的Python库(requests和beautifulsoup4)以及它们的依赖项。你可以使用以下命令来安装这些库:

powershell 复制代码
pip install requests beautifulsoup4

如果想要图片

powershell 复制代码
print("Runoob")

import requests
from bs4 import BeautifulSoup

# 发起请求并获取网页内容
url = '可以用上面的链接🔗'
response = requests.get(url)
html_content = response.text

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

# 提取书籍标题和价格
books = soup.find_all('article', class_='product_pod')

for book in books:
    img_element = book.find('img', class_='thumbnail')
    img_url = img_element.get('src')
    title = book.h3.a['title']
    price = book.find('p', class_='price_color').text

    print('图片:', img_url)
    print('书名:', title)
    print('价格:', price)
    print('---')
相关推荐
呆萌很11 分钟前
python 项目迁移
python
清水白石00817 分钟前
《requests vs httpx:Python 网络请求库的全面对比与实战指南》
网络·python·httpx
MediaTea34 分钟前
大学 Python 编程基础(合集)
开发语言·python
Nautiluss38 分钟前
一起玩XVF3800麦克风阵列(十)
linux·人工智能·python·音频·语音识别·实时音视频·dsp开发
BoBoZz1941 分钟前
MultiBlockDataSet 复合感知与非复合感知
python·vtk·图形渲染·图形处理
兔子小灰灰1 小时前
jetson安装pytorch
人工智能·pytorch·python
Swizard2 小时前
拒绝“裸奔”上线:FastAPI + Pytest 自动化测试实战指南
python
Ven%3 小时前
从单轮问答到连贯对话:RAG多轮对话技术详解
人工智能·python·深度学习·神经网络·算法
谈笑也风生4 小时前
经典算法题型之复数乘法(二)
开发语言·python·算法
先知后行。4 小时前
python的类
开发语言·python