网络爬虫python代码
时间: 2023-07-05 07:35:13 浏览: 59
以下是一个简单的 Python 网络爬虫示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 发送 HTTP GET 请求
url = 'https://www.example.com'
response = requests.get(url)
# 解析 HTML 页面
soup = BeautifulSoup(response.text, 'html.parser')
# 获取页面标题
title = soup.title.string
print(title)
# 查找所有链接
links = []
for link in soup.find_all('a'):
links.append(link.get('href'))
print(links)
```
这段代码使用 requests 库向指定 URL 发送 HTTP GET 请求,然后使用 BeautifulSoup 库解析 HTML 页面。我们可以使用 BeautifulSoup 的各种方法来查找特定的 HTML 元素,例如页面标题和链接。在这个例子中,我们查找了页面中的所有链接,并将它们添加到一个列表中。
相关问题
网络爬虫python代码新闻
以下是一个简单的Python网络爬虫代码示例,用于从新闻网站中获取标题和链接:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com/news' # 新闻网站的URL
response = requests.get(url) # 发送GET请求
html = response.content # 获取HTML内容
soup = BeautifulSoup(html, 'html.parser') # 解析HTML
# 查找新闻标题和链接
for news in soup.find_all('div', {'class': 'news'}):
title = news.find('a').text.strip() # 获取标题并去除前后空格
link = news.find('a')['href'] # 获取链接
print(title, link) # 打印标题和链接
```
请注意,这只是一个示例代码,实际使用时需要根据具体的网站结构进行调整和修改。此外,在进行网络爬取时需要遵守相关法律法规和网站的使用条款,以免引起法律问题。
网络爬虫python照片代码
当涉及到网络爬虫和图片下载时,Python提供了一些强大的库和工具来实现这个功能。以下是一个简单的示例代码,用于使用Python进行网络爬虫图片下载:
```python
import requests
import os
def download_image(url, save_path):
response = requests.get(url)
if response.status_code == 200:
with open(save_path, 'wb') as f:
f.write(response.content)
print("图片下载成功!")
else:
print("图片下载失败!")
# 设置图片保存路径
save_dir = './images'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# 图片URL
image_url = 'https://example.com/image.jpg'
# 下载图片
download_image(image_url, os.path.join(save_dir, 'image.jpg'))
```
这段代码使用了`requests`库来发送HTTP请求并获取图片的二进制数据,然后将数据保存到本地文件中。你可以根据自己的需求修改代码,例如处理多个图片URL、设置不同的保存路径等。