基于豆瓣爬虫的股票爬取
豆瓣电影爬虫为大佬的代码
import requests
from bs4 import BeautifulSoup
import pandas as pd
# 构造分页数字列表
page_indexs = range(0, 250, 25)
def download_all_htmls():
"""
下载所有列表页面的HTML,用于后续的分析
"""
htmls = []
for idx in page_indexs:
url = f"https://movie.douban.com/top250?start={idx}&filter="
print("craw html:", url)
r = requests.get(url,
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"})
if r.status_code != 200:
raise Exception("error")
htmls.append(r.text)
return htmls
# 执行爬取
htmls = download_all_htmls()
def parse_single_html(html):
"""
解析单个HTML,得到数据
@return list({"link", "title", [label]})
"""
soup = BeautifulSoup(html, 'html.parser')
article_items = (
soup.find("div", class_="article")
.find("ol", class_="grid_view")
.find_all("div", class_="item")
)
datas = []
for article_item in article_items:
rank = article_item.find("div", class_="pic").find("em").get_text()
info = article_item.find("div", class_="info")
title = info.find("div", class_="hd").find("span", class_="title").get_text()
stars = (
info.find("div", class_="bd")
.find("div", class_="star")
.find_all("span")
)
rating_star = stars[0]["class"][0]
rating_num = stars[1].get_text()
comments = stars[3].get_text()
datas.append({
"rank": rank,
"title": title,
"rating_star": rating_star.replace("rating", "").replace("-t", ""),
"rating_num": rating_num,
"comments": comments.replace("人评价", "")
})
return datas

本文是关于Python爬虫学习的笔记,详细介绍了如何使用BeautifulSoup库从豆瓣电影页面抓取数据。首先讲解了request库和BeautifulSoup库的作用,接着阐述了pandas在数据处理和保存为Excel表格中的应用。代码中通过分析网页结构,逐层定位到目标数据,并使用find和find_all函数。此外,还讨论了反爬虫策略,包括设置headers模仿浏览器行为,以及如何将数据存储到MySQL数据库。
最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



