温馨提示×

Pycharm怎么爬取网页文本和图片

小亿
179
2023-08-17 19:22:54
栏目: 编程语言

要使用Pycharm爬取网页文本和图片,你可以使用以下步骤:

  1. 导入所需的库:requestsbeautifulsoup4
import requests
from bs4 import BeautifulSoup
  1. 使用requests库发送HTTP请求获取网页内容。
url = "https://example.com"  # 替换为你想要爬取的网页URL
response = requests.get(url)
  1. 使用BeautifulSoup库解析网页内容。
soup = BeautifulSoup(response.content, 'html.parser')
  1. 爬取文本:使用BeautifulSoup的方法选择和提取你想要的文本内容。
text = soup.get_text()  # 获取网页所有的文本内容
  1. 爬取图片:使用BeautifulSoup的方法选择和提取你想要的图片。
images = soup.find_all('img')  # 找到网页中的所有<img>标签
for img in images:
img_url = img['src']  # 图片的URL
img_response = requests.get(img_url)  # 请求图片的URL
with open('image.jpg', 'wb') as f:
f.write(img_response.content)  # 将图片内容写入文件

注意:上述代码中的https://example.comimage.jpg需要替换为你想要爬取的网页URL和保存图片的文件名。

希望这能帮到你!

0