python re模块爬取豆瓣250海报
时间: 2023-11-17 13:04:47 浏览: 47
以下是使用Python re模块爬取豆瓣250电影海报的代码:
```python
import requests
import re
# 获取网页内容
url = 'https://movie.douban.com/top250'
response = requests.get(url)
content = response.text
# 使用正则表达式匹配海报链接
pattern = re.compile(r'<img.*?src="(.*?)"', re.S)
results = re.findall(pattern, content)
# 下载海报
for i, result in enumerate(results):
response = requests.get(result)
with open(f'{i}.jpg', 'wb') as f:
f.write(response.content)
```
该代码首先使用requests模块获取豆瓣电影Top250的网页内容,然后使用正则表达式匹配出所有海报的链接,最后使用requests模块下载海报并保存到本地。
相关问题
python代码实现爬取豆瓣电影250
好的,我可以帮你回答这个问题。以下是实现爬取豆瓣电影250的Python代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/top250'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
def get_movie_info(movie_list):
for movie in movie_list:
movie_name = movie.find('span', class_='title').get_text()
movie_rating = movie.find('span', class_='rating_num').get_text()
print(movie_name, movie_rating)
def get_movie_list(url):
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
movie_list = soup.find_all('div', class_='info')
return movie_list
if __name__ == '__main__':
for i in range(0, 250, 25):
url = f'https://movie.douban.com/top250?start={i}&filter='
movie_list = get_movie_list(url)
get_movie_info(movie_list)
```
这个代码使用requests库和BeautifulSoup库,发送网络请求获取网页源码,然后使用BeautifulSoup来解析源码,最后将豆瓣电影250的电影名称和评分输出到控制台。通过遍历不同的URL链接,我们可以获取豆瓣电影250的所有电影信息。
python用selenium爬取豆瓣电影top250
好的,以下是使用python和selenium爬取豆瓣电影top250的代码示例:
```python
from selenium import webdriver
url = 'https://movie.douban.com/top250'
driver = webdriver.Chrome() # 需要安装Chrome浏览器和对应版本的chromedriver
driver.get(url)
# 循环获取每一页的电影信息
while True:
# 获取当前页的电影信息
movie_list = driver.find_elements_by_xpath('//div[@class="info"]')
for movie in movie_list:
title = movie.find_element_by_xpath('div[@class="hd"]/a/span[@class="title"]').text
rating = movie.find_element_by_xpath('div[@class="bd"]/div[@class="star"]/span[@class="rating_num"]').text
print(title, rating)
# 判断是否有下一页,如果没有则结束循环
next_page = driver.find_element_by_xpath('//span[@class="next"]/a')
if not next_page:
break
# 进入下一页
next_page.click()
driver.quit()
```
这段代码会打印出豆瓣电影top250中每部电影的名称和评分。注意需要安装Chrome浏览器和对应版本的chromedriver,并将chromedriver的路径添加到系统环境变量中。