python爬虫猫眼电影排行top100实例

今天是个好天气,培训了一个月了,可以看的懂python代码,一直对爬虫比较感兴趣,今天星期六没上课就看视频,跟着老师敲代码,中间各种错误,到饭点了才弄好,成功爬取!这个时刻也是值得纪念的,心情和天气一样晴朗。感兴趣的朋友也可以照下面的代码自己敲一遍,运行一下看看效果。
import requests,re
from requests.exceptions import RequestException
import json
def get_one_page(url):
try:
response = requests.get(url)
if response.status_code == 200 :
return response.text
return None
except RequestException :
return None
def parse_one_page(html):
pattern = re.compile(’

. ?board-index.?>(\d+)</i. ?data-src="(.?)". ?name"><a’
+’.
?>(. ?).?star">(. ?)

.?releasetime">(. ?)’
+’.
?integer">(. ?).?fraction">(. ?).?’,re.S)
items = re.findall(pattern,html)
for item in items:
yield {
‘index’:item[0],
‘image’: item[1],
‘title’: item[2],
‘actor’: item[3].strip()[3:],
‘time’: item[4].strip()[5:],
‘score’: item[5]+item[6],
}
def write_to_file(content):
with open(‘result.txt’,‘a’,encoding=‘utf-8’) as f :
f.write(json.dumps(content,ensure_ascii=False)+’\n’)
f.close()
def main(offset):
url = “ https://maoyan.com/board/4?offset=”+str(offset)
html = get_one_page(url)
parse_one_page(html)
for item in parse_one_page(html):
print(item)
write_to_file(item)
if name == ‘ main’:
for i in range(10):
main(i*10)

告诉你使我达到目标的奥秘吧,我唯一的力量就是我的坚持精神。

猜你喜欢

转载自blog.csdn.net/weixin_44651916/article/details/88594966