要使用Pycharm爬取网页文本和图片,你可以使用以下步骤:
- 导入所需的库:
requests
和beautifulsoup4
。
import requests from bs4 import BeautifulSoup
- 使用
requests
库发送HTTP请求获取网页内容。
url = "https://example.com" # 替换为你想要爬取的网页URL response = requests.get(url)
- 使用
BeautifulSoup
库解析网页内容。
soup = BeautifulSoup(response.content, 'html.parser')
- 爬取文本:使用
BeautifulSoup
的方法选择和提取你想要的文本内容。
text = soup.get_text() # 获取网页所有的文本内容
- 爬取图片:使用
BeautifulSoup
的方法选择和提取你想要的图片。
images = soup.find_all('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.com
和image.jpg
需要替换为你想要爬取的网页URL和保存图片的文件名。
希望这能帮到你!