以下是一个示例,用于爬取一个公开的示例网站(http://books.toscrape.com),并提取书籍的标题和价格:
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').textprint('书名:', title)print('价格:', price)print('---')
这个示例使用了一个公开的书籍网站(http://books.toscrape.com),通过发送HTTP请求获取网页内容,并使用BeautifulSoup解析网页内容。然后,它找到所有的书籍信息,并提取书名和价格,并将它们打印出来。
运行脚本
python spider.py
请确保你已经安装了所需的Python库(requests和beautifulsoup4)以及它们的依赖项。你可以使用以下命令来安装这些库:
pip install requests beautifulsoup4
如果想要图片
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').textprint('图片:', img_url)print('书名:', title)print('价格:', price)print('---')