Pycharm怎么爬取網(wǎng)頁(yè)文本和圖片

小億
225
2023-08-17 19:22:54

要使用Pycharm爬取網(wǎng)頁(yè)文本和圖片,你可以使用以下步驟:

  1. 導(dǎo)入所需的庫(kù):requestsbeautifulsoup4。
import requests
from bs4 import BeautifulSoup
  1. 使用requests庫(kù)發(fā)送HTTP請(qǐng)求獲取網(wǎng)頁(yè)內(nèi)容。
url = "https://example.com"  # 替換為你想要爬取的網(wǎng)頁(yè)URL
response = requests.get(url)
  1. 使用BeautifulSoup庫(kù)解析網(wǎng)頁(yè)內(nèi)容。
soup = BeautifulSoup(response.content, 'html.parser')
  1. 爬取文本:使用BeautifulSoup的方法選擇和提取你想要的文本內(nèi)容。
text = soup.get_text()  # 獲取網(wǎng)頁(yè)所有的文本內(nèi)容
  1. 爬取圖片:使用BeautifulSoup的方法選擇和提取你想要的圖片。
images = soup.find_all('img')  # 找到網(wǎng)頁(yè)中的所有<img>標(biāo)簽
for img in images:
img_url = img['src']  # 圖片的URL
img_response = requests.get(img_url)  # 請(qǐng)求圖片的URL
with open('image.jpg', 'wb') as f:
f.write(img_response.content)  # 將圖片內(nèi)容寫(xiě)入文件

注意:上述代碼中的https://example.comimage.jpg需要替換為你想要爬取的網(wǎng)頁(yè)URL和保存圖片的文件名。

希望這能幫到你!

0