python爬虫简单实例
时间: 2024-06-27 08:00:43 浏览: 128
Python爬虫是一个用于自动化数据抓取的工具,常用于网站数据的收集。一个简单的Python爬虫实例通常是使用`requests`库获取网页内容,然后用`BeautifulSoup`或`lxml`解析HTML。以下是一个使用`requests`和`BeautifulSoup`抓取网页标题的基本示例:
```python
# 导入所需库
import requests
from bs4 import BeautifulSoup
# 定义目标URL
url = "https://www.example.com"
# 使用requests获取网页内容
response = requests.get(url)
# 检查请求状态码
if response.status_code == 200:
# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 找到网页标题
title = soup.title.string
# 打印标题
print("网页标题:", title)
else:
print("请求失败,状态码:", response.status_code)
相关问题
python爬虫简单小实例
以下是一个简单的Python爬虫实例,可以爬取豆瓣电影页面的电影名称和评分:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/top250'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
movies = soup.find_all('div', class_='hd')
for movie in movies:
title = movie.a.span.text
rating = movie.parent.find('span', class_='rating_num').text
print(title + ' ' + rating)
```
该程序首先使用`requests`库向豆瓣电影页面发送GET请求,并使用`BeautifulSoup`库解析网页内容。然后,程序从页面中找到所有包含电影名称和评分的`<div>`元素,依次提取电影名称和评分,并输出到控制台。
python爬虫requests实例
好的,以下是一个简单的使用 Python requests 库进行网页爬取的示例代码:
```python
import requests
url = "https://www.baidu.com"
response = requests.get(url)
print(response.text)
```
上述代码中,我们首先导入 requests 库,然后指定要爬取的网页 URL,使用 requests.get() 方法获取页面内容,最后打印出页面的 HTML 内容。
需要注意的是,有些网站会对爬虫进行限制或封禁,因此在进行网页爬取时需要注意遵守相关法律规定和网站的使用协议。
阅读全文
相关推荐











