Python 爬虫实例
时间: 2023-11-05 07:22:24 浏览: 58
当然,我可以给你提供一个简单的 Python 爬虫实例。以下是一个使用 requests 和 BeautifulSoup 库的示例,用来爬取一个网页的标题和链接:
```python
import requests
from bs4 import BeautifulSoup
# 发起请求
url = 'https://www.example.com'
response = requests.get(url)
# 解析 HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 获取标题
title = soup.title.string
print('页面标题:', title)
# 获取所有链接
links = soup.find_all('a')
for link in links:
href = link.get('href')
print(href)
```
在这个示例中,我们首先使用 requests 库发起了一个 GET 请求,并获取了网页的响应。然后,使用 BeautifulSoup 库解析了网页的 HTML 内容。接着,我们从解析后的内容中提取出了页面的标题,并将它打印出来。最后,我们使用 `find_all` 方法找到了所有的链接,并逐个打印出来。
请注意,这只是一个简单的示例,实际的爬虫可能需要处理更复杂的网页结构和数据提取。同时,爬取网页时需要尊重网站的规则和政策,避免对网站造成不必要的负担或违反法律法规。
相关问题
python 爬虫实例
下面是一个简单的 Python 爬虫实例,它可以从网站上获取并输出新闻标题和链接:
```
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com/news'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
for news in soup.find_all('div', class_='news-item'):
title = news.find('a', class_='title').text.strip()
link = news.find('a', class_='title')['href']
print(title)
print(link)
```
这个例子使用了 requests 库来发送 HTTP 请求,使用 BeautifulSoup 库来解析 HTML 页面。在这个例子中,我们首先用 requests 库获取了一个网址的 HTML 页面,然后使用 BeautifulSoup 库来解析这个页面,并找到所有的新闻标题和链接。最后,我们循环遍历每个新闻条目,并打印出标题和链接。
Python爬虫实例
下面是一个使用 Python 爬虫爬取网页信息的简单实例:
```python
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
print(soup.prettify())
```
这段代码使用 `requests` 库发送了一个 GET 请求,将网页的 HTML 内容获取到并用 `BeautifulSoup` 解析。然后使用 `soup.prettify()` 方法将解析后的内容打印出来。
根据需求可以添加更多的代码,筛选出需要的信息。