替朋友做网站,wordpress get_post_custom_values,wordpress需要钱吗,网站域名费一年多少钱关于整理日常练习的一些爬虫小练习#xff0c;可用作学习使用。
爬取项目以学习为主#xff0c;尽可能使用更多的模块进行练习#xff0c;而不是最优解。
爬虫概要
示例python 库爬取模块request解析模块BeautifulSoup存储类型list#xff08;方便存入数据库#xff09…
关于整理日常练习的一些爬虫小练习可用作学习使用。
爬取项目以学习为主尽可能使用更多的模块进行练习而不是最优解。
爬虫概要
示例python 库爬取模块request解析模块BeautifulSoup存储类型list方便存入数据库
解析 代码示例 # -*- coding: utf-8 -*-import requests
from requests.exceptions import ReadTimeout, ConnectionError, RequestException
from bs4 import BeautifulSoup# 爬虫主体
def get_page(url):headers {Connection: keep-alive,Cache-Control: max-age0,User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36,Accept: text/html,application/xhtmlxml,application/xml;q0.9,image/webp,image/apng,*/*;q0.8,application/signed-exchange;vb3,Referer: https://maoyan.com/board,}try:response requests.get(urlurl, headersheaders).textreturn responseexcept ReadTimeout: # 访问超时的错误print(Timeout)except ConnectionError: # 网络中断连接错误print(Connect error)except RequestException: # 父类错误print(Error)# 解析网页
def parse_page(html):soup BeautifulSoup(html, lxml)grid soup.find(nameol, attrs{class: grid_view})movie_list grid.find_all(li)for movie in movie_list:rank movie.find(nameem).getText()name movie.find(namespan, attrs{class: title}).getText()rating_num movie.find(namespan, attrs{class: rating_num}).getText()# bd movie.find(namep).getText().strip().replace( , \n).replace(...\n , ...\n).replace( / , \n).split(\n) # 头皮发麻字符串分解系列因为练习没用 re果然原生字符串处理麻烦的一匹strip去除空格replace替换旨在将不同信息分类存储到不同的参数如导演、主演、上映时间、上映时间和电影类型bd movie.find(namep).getText().strip().replace( , \n).replace(...\n , ...\n).replace( / , \n).split(\n) # 头皮发麻字符串分解系列因为练习没用 re果然原生字符串处理麻烦的一匹strip去除空格replace替换旨在将不同信息分类存储到不同的参数如导演、主演、上映时间、上映时间和电影类型# 豆瓣有些主演没有。。。贼蛋疼为了简便只能写个烂代码再增加一次了if len(bd) 4:bd.insert(1, 没爬到)inq movie.find(namespan, attrs{class: inq})# 处理 inq 为空的情况if not inq:inq 暂无else:inq inq.getText()# 这里直接存储到字典方便存到数据库douBanDict[rank] rankdouBanDict[name] namedouBanDict[director] bd[0]douBanDict[actor] bd[1]douBanDict[release_time] bd[2].strip() # 某些列表有空格直接strip()去除空格douBanDict[country] bd[3]douBanDict[movie_types] bd[4]douBanDict[rating_num] rating_numdouBanDict[inq] inqdouBanList.append(str(douBanDict)) # 字典先转为字符串再累加到列表中否则无法字典值会一直变return douBanListif __name__ __main__:douBanList []douBanDict {}for start in range(0, 250, 25):url https://movie.douban.com/top250?start{}filter.format(start)html get_page(url)douBanList parse_page(html)print(douBanList)
数据存储
直接是列表格式同时包含各个电影信息的字典。