注:初学爬虫,本节仅使用requests库和使用正则作为解析工具
最近学习爬虫,找个比较简单的网页练习了一下,作为初入爬虫的小白,不足之处还请大家多多指教。
一、分析url
首先,打开目标站点/board/4,打开之后便看到榜单信息:
排名第一的电影是霸王别姬,页面中可以看到的信息有电影名称,主演,上映时间,电影封面,评分,排名等。
页面最下面有分页列表,切换到第2页,看看url发生了哪些变化。
可以看到第2页的url为/board/4?offset=10,url与第1页相比发生了些变化。再分别把第3页和第4页的url拿来比较一下。
第1页:/board/4
第2页:/board/4?offset=10
第3页:/board/4?offset=20
第4页:/board/4?offset=30
貌似发现了一些规律,将第1页改为/board/4?offset=0试试?
发现依然可以找到第1页,可以发现offset代表了偏移量,如果偏移量为n,则显示电影的序号就是n+1--n+10,每页10条,总共100条,就是10页,只需分开请求10次,每次的偏移量分别为0,10,20,30,...,90即可,再得到页面信息后,使用正则就可以得到电影的排名主演等信息了。
二、获取第一页
1、获取页面内容,将其封装成get_one_page()方法,传入url参数,之后使用main()调用该方法返回网页内容:
# 请求网页,返回网页内容def get_one_page(url):headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',}response = requests.get(url, headers=headers)if response.status_code == 200:return response.textreturn Nonedef main(offset):url = '/board/4?offset=' + str(offset)html = get_one_page(url)print(html)
2、正则提取
观察网页代码可发现,每条电影信息都由一个dd标签括起来,二电影的其他信息已经分别标出。
获取排名信息的正则表达式:<dd>.*?board-index.*?>(.*?)</i>
再获取电影封面:<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)"
再提取电影名,主演,上映时间等信息,同样的道理,最后正则表达式为:
'<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)"'+'.*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>'+'.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>'+'.*?fraction.*?>(.*?)</i>.*?</dd>'
有了正则表达式接下来我们在定义解析页面的方法,parse_one_page(),传入参数html
# 使用正则将需要的数据剥离def parse_one_page(html):pattern = pile('<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)"'+'.*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>'+'.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>'+'.*?fraction.*?>(.*?)</i>.*?</dd>',re.S)res = re.findall(pattern, html)for i in res:yield {'排名': i[0],'封面': i[1],'影片名称': i[2],'主演': i[3].strip()[3:],'上映时间': i[4].strip()[5:],'评分': i[5].strip() + i[6].strip(),}
3、写入文件
使用json将字典序列化,指定参数ensure_ascii=False,保证写入的结果是中文。
def write_to_file(content):with open('猫眼电影排行TOP100.txt', 'a', encoding='utf-8') as f:f.write(json.dumps(content, ensure_ascii=False) + '\n')
4、优化main函数,将单页电影数据写入到文件。
def main(offset):url = '/board/4?offset=0'html = get_one_page(url)for item in parse_one_page(html):print(item)write_to_file(item)
5、分页爬取
要实现分页爬取,只需要分别给offset传入不同的值即可,添加如下调用并修改main函数
def main(offset):url = '/board/4?offset=' + str(offset)html = get_one_page(url)for item in parse_one_page(html):print(item)write_to_file(item)if __name__ == '__main__':for i in range(10):main(offset=i*10)
至此我们将猫眼电影的top100已经爬取完了,完整代码如下:
import requestsimport re, json# 请求网页,返回响应体def get_one_page(url):headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',}response = requests.get(url, headers=headers)if response.status_code == 200:return response.textreturn None# 使用正则将需要的数据剥离def parse_one_page(html):pattern = pile('<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)"'+'.*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>'+'.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>'+'.*?fraction.*?>(.*?)</i>.*?</dd>',re.S)res = re.findall(pattern, html)for i in res:yield {'排名': i[0],'封面': i[1],'影片名称': i[2],'主演': i[3].strip()[3:],'上映时间': i[4].strip()[5:],'评分': i[5].strip() + i[6].strip(),}# 将结果写入到文件def write_to_file(content):with open('猫眼电影排行TOP100.txt', 'a', encoding='utf-8') as f:f.write(json.dumps(content, ensure_ascii=False) + '\n')def main(offset):url = '/board/4?offset=' + str(offset)html = get_one_page(url)for item in parse_one_page(html):print(item)write_to_file(item)if __name__ == '__main__':for i in range(10):main(offset=i*10)
参考《Python3 网络爬虫开发实战》--崔庆才