例举一个用python爬取网站的例子
时间: 2024-05-06 09:19:34 浏览: 19
以下是一个简单的用Python爬取豆瓣电影信息的例子:
```
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/top250'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
movies = []
for movie in soup.select('.grid_view li'):
title = movie.select('.title')[0].text
rating = movie.select('.rating_num')[0].text
year = movie.select('.bd p')[1].text.split()[0]
movies.append({'title': title, 'rating': rating, 'year': year})
for movie in movies:
print(movie['title'], movie['rating'], movie['year'])
```
这个例子使用了Requests库来获取网页内容,用BeautifulSoup库来解析HTML文档,然后从豆瓣电影Top250页面中提取了电影的标题、评分和年份,并将它们存储在一个列表中。最后,程序打印出了每部电影的标题、评分和年份。
相关问题
怎么用python爬取一个网站的表格
爬取一个网站的表格通常需要使用到Python中的requests和BeautifulSoup这两个库。
首先,我们需要使用requests库来获取网站的HTML源代码。例如,如果我们想要爬取一个名为example.com的网站的表格,可以使用以下代码:
```python
import requests
url = "https://www.example.com/table.html"
response = requests.get(url)
html = response.text
```
接下来,我们需要使用BeautifulSoup库来解析HTML源代码,并提取我们想要的表格数据。假设我们要提取的表格在HTML源代码中的标签为`<table>`,我们可以使用以下代码:
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
table = soup.find('table')
# 提取表格数据
rows = table.find_all('tr')
for row in rows:
cols = row.find_all('td')
for col in cols:
print(col.text, end='\t')
print()
```
上述代码中,我们首先使用BeautifulSoup库将HTML源代码解析为一个BeautifulSoup对象。然后,我们使用该对象的`find()`方法查找HTML源代码中的表格标签,并将其存储在`table`变量中。最后,我们使用`find_all()`方法提取表格中的所有行,然后遍历每一行并提取相应的单元格数据。
当然,上述代码只是一个示例,实际上爬取表格的方式可能因网站结构而异。但是,以上基本思路可以作为一个通用的参考。
帮我写一个用Python爬取网站视频并下载的代码
好的,这是一个使用 Python 爬取网站视频并下载的代码示例:
```
import requests
url = "http://example.com/video.mp4"
response = requests.get(url)
with open("video.mp4", "wb") as file:
file.write(response.content)
```
这是一个简单的代码,使用 `requests` 库从指定的 URL 获取视频内容,然后使用 `open` 函数写入本地文件,存为 "video.mp4"。
请注意,有些网站可能会阻止爬取视频,因此在使用本代码前请先确保您有权访问该网站的视频。