要使用Pycharm爬取網(wǎng)頁(yè)文本和圖片,你可以使用以下步驟:
requests
和beautifulsoup4
。import requests
from bs4 import BeautifulSoup
requests
庫(kù)發(fā)送HTTP請(qǐng)求獲取網(wǎng)頁(yè)內(nèi)容。url = "https://example.com" # 替換為你想要爬取的網(wǎng)頁(yè)URL
response = requests.get(url)
BeautifulSoup
庫(kù)解析網(wǎng)頁(yè)內(nèi)容。soup = BeautifulSoup(response.content, 'html.parser')
BeautifulSoup
的方法選擇和提取你想要的文本內(nèi)容。text = soup.get_text() # 獲取網(wǎng)頁(yè)所有的文本內(nèi)容
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.com
和image.jpg
需要替換為你想要爬取的網(wǎng)頁(yè)URL和保存圖片的文件名。
希望這能幫到你!