溫馨提示×

Pycharm怎么爬取網頁文本和圖片

小億
286
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女