爬虫步骤:
1.获取数据
2.解析数据
3.保存数据
1.获取数据:
1)先确定一个url:url=”https://movie.douban.com/top250?start="
2)再准备好header:headers={"User-Agent",“host”,“cookies”}
3)发送request请求,包含headers等信息:request=urllib.request.Request(url,headers=head) #urllib.request发送请求
4)获取响应:response=urllib.request.urlopen(request) #urllib.urlopen()获取响应
5)读取响应:html=response.read().decode("utf-8") #read读取页面内容
2.解析数据:
1)使用beautifulsoup解析网页:(beautifulsoup将复杂html转化为复杂的树形结构,每个节点都是python对象)
soup= bs4.BeautifulSoup(html, "html.parser") #创建一个soup对象,html是一个网页内容, 使用"html.parser"解析器。
2)之后使用正则表达式提取想要的字符串:
soup.find_all('div', class_="item") #beautifulsoup中的find_all()找到所有匹配结果出现的地方,返回的是一个列表!
findLink = re.compile(r'<a href="(.*?)">') #用正则表达式限定要找的字符串
link = re.findall(findLink,item)[0] #re.findall (返回string中所有与pattern相匹配的全部字串,返回形式为数组)re.findall(pattern, string, flags
=
0
)
3.保存数据:
1)保存到Excel中:
2)保存到数据库中(sqlite):
3)保存为文本: